why comparator ?
-
comparable : adj
-
comparator : n
Some class can't be changed , which like Map , Set and their subclass . They are given being unchangeable . Thus , we can't
public TreeMap implements comparable{
...
}
So , here comparator works .
// mapCompare is the class with comparator()
TreeMap<String,Integer> map = new TreeMap<String,Integer>( new mapCompare() );
// The configure <String> is same as the key of *TreeMap*
class mapCompare implements Comparator<String > {
public int compare( String o1, String o2){
o1.compareTo(o2);
}
Code
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class mapSortedByKey {
public static void main(String[] args) {
// New one map
TreeMap<String, Integer> map = new TreeMap<String, Integer>(new mapCompare());
map.put("E", 1);
map.put("A", 2);
map.put("B", 3);
map.put("C", 4);
map.put("D", 5);
// print
/*for( Map.Entry<String,Integer> one: map.entrySet() ){
System.out.println(one.getKey()+":"+one.getValue());
}
*/
Iterator<Map.Entry<String,Integer> > iter = map.entrySet().iterator();
while(iter.hasNext()){
Map.Entry<String,Integer> one = iter.next();
System.out.println(one.getKey() +": "+one.getValue());
}
}
}
class mapCompare implements Comparator<String> {
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
}
E: 1
D: 5
C: 4
B: 3
A: 2