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
}
}
sorted_map在初始化的時候,你給了它Comparator, 所以sorted_map.putAll(map)的時候,其實就是把map裡的每個entry放進sorted_map裡,每放一個,sorted_map就會呼叫Comparator的compare方法來比較一下,決定放在哪個位置,這樣sorted_map的entry就都是依照Comparator的順序規則來排列的啦。