Java 根据值对treemap进行排序,并将其作为treemap agin返回。

Java 根据值对treemap进行排序,并将其作为treemap agin返回。,java,treemap,key-value-store,Java,Treemap,Key Value Store,我有树形图,我用下面的代码按值排序。如何再次以树映射的形式获得结果 static <K, V extends Comparable<? super V>> SortedSet<Map.Entry<K, V>> entriesSortedByValues( Map<K, V> map) { SortedSet<Map.Entry<K, V>> sortedEntries = new Tree

我有树形图,我用下面的代码按值排序。如何再次以树映射的形式获得结果

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;
}

static您正在创建一个
TreeSet
,而您需要创建一个
TreeMap
。传递给
TreeMap
的比较器将使用作为参数传递的
map
来获取值并进行比较

将您的方法更改为:

static <K, V extends Comparable<? super V>> TreeMap<K, V> entriesSortedByValues(final Map<K, V> map) {
    TreeMap<K, V> sortedEntries = new TreeMap<K, V>(new Comparator<K>() {
      @Override
      public int compare(K o1, K o2) {
        return map.get(o1).compareTo(map.get(o2));
      }
    });
    sortedEntries.putAll(map);
    return sortedEntries;
}

静态
TreeMap
总是按键排序;不清楚您在问什么。为什么要在那里创建
TreeSet
,而不是
TreeMap
?您必须在生成的排序映射中指定所需的键和值。目前,这个问题还不清楚。是的,确实如此,但这是一个技巧,因为每次调用键比较器时,它都会得到相应的值。就性能而言,这肯定很糟糕……没有检查你的
map.get(o1).compareTo(map.get(o2))
@AbbéRésina没有那么可怕,因为
map#get
是一个
O(1)
操作。@RohitJain不是O(logN)?@AbbéRésina好吧,什么样的排序比
O(logN)
public static void main(String args[]) {
  Map<Integer, Integer> map = new HashMap<Integer, Integer>();
  map.put(1, 3);
  map.put(3, 1);
  map.put(5, 6);
  map.put(2, 10);
  // Prints: {3=1, 1=3, 5=6, 2=10}
  System.out.println(entriesSortedByValues(map));
}