小编典典

Java TreeMap按值排序

java

我想编写一个比较器,使我可以按值而不是默认自然顺序对TreeMap进行排序。

我尝试过类似的方法,但无法找出问题所在:

import java.util.*;

class treeMap {
    public static void main(String[] args) {
        System.out.println("the main");
        byValue cmp = new byValue();
        Map<String, Integer> map = new TreeMap<String, Integer>(cmp);
        map.put("de",10);
        map.put("ab", 20);
        map.put("a",5);

        for (Map.Entry<String,Integer> pair: map.entrySet()) {
            System.out.println(pair.getKey()+":"+pair.getValue());
        }
    }
}

class byValue implements Comparator<Map.Entry<String,Integer>> {
    public int compare(Map.Entry<String,Integer> e1, Map.Entry<String,Integer> e2) {
        if (e1.getValue() < e2.getValue()){
            return 1;
        } else if (e1.getValue() == e2.getValue()) {
            return 0;
        } else {
            return -1;
        }
    }
}

我想我要问的是:我可以Map.Entry通过比较器吗?


阅读 653

收藏
2020-02-27

共1个答案

小编典典

你不能TreeMap对值本身进行排序,因为这违反了SortedMap规范:

一个Map是还提供了一个总体排序它的键。

但是,使用外部集合,你始终Map.entrySet()可以根据需要按键,值或什至两者的组合(!!)进行排序。

这是一个通用方法,如果的值为,则返回的SortedSetof :Map.EntryMapComparable

static <K,V extends Comparable<? super V>>
SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
    SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
        new Comparator<Map.Entry<K,V>>() {
            @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                int res = e1.getValue().compareTo(e2.getValue());
                return res != 0 ? res : 1;
            }
        }
    );
    sortedEntries.addAll(map.entrySet());
    return sortedEntries;
}

现在,你可以执行以下操作:

    Map<String,Integer> map = new TreeMap<String,Integer>();
    map.put("A", 3);
    map.put("B", 2);
    map.put("C", 1);   

    System.out.println(map);
    // prints "{A=3, B=2, C=1}"
    System.out.println(entriesSortedByValues(map));
    // prints "[C=1, B=2, A=3]"

请注意,如果你尝试修改SortedSet自身或Map.Entry内部,则将发生时髦的事情,因为它不再像原来那样entrySet()是原始地图的“视图” 。

一般而言,按地图的值对地图的条目进行排序的需求是不典型的。

Note on == for Integer

你的原始比较器Integer使用比较==。这几乎总是错的,因为==有Integer操作数是一个参考平等,没有平等的价值。

    System.out.println(new Integer(0) == new Integer(0)); // prints "false"!!!
2020-02-27