public class Testing {
public static void main(String[] args) {
HashMap<String,Double> map = new HashMap<String,Double>();
ValueComparator bvc = new ValueComparator(map);
TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);
sorted_map.putAll(map);
}
}
class ValueComparator implements Comparator<String> {
Map<String, Double> base;
public ValueComparator(Map<String, Double> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
When sorted_map is initialized, you give it a Comparator, so when sorted_map.putAll(map), you actually put each entry in the map into sorted_map. Every time you put one, sorted_map will call the compare method of Comparator. Let's compare and decide where to put it, so that the entries of sorted_map are arranged according to the order rules of Comparator.