java中根据map的value进行排序

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
    }
}
阅读 5.1k
2 个回答

sorted_map在初始化的时候,你给了它Comparator, 所以sorted_map.putAll(map)的时候,实际上是把map里的每个entry放进sorted_map里,每放一个,sorted_map就会调用Comparator的compare方法来比较一下,决定放在哪个位置,这样sorted_map的entry就都是按照Comparator的顺序规则来排列的啦。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题