树状图按值排序

2022-08-31 07:08:58

我想写一个比较器,让我按值而不是默认的自然排序来对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


答案 1

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

进一步提供对其密钥的总排序Map

但是,使用外部集合,您始终可以根据需要对Map.entrySet()进行排序,无论是按键,值还是两者的组合(!!)。

下面是一个泛型方法,它返回 a of ,给定 a 的值为:SortedSetMap.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]"

请注意,如果您尝试修改本身或内部,就会发生时髦的事情,因为这不再是原始地图的“视图”。SortedSetMap.EntryentrySet()

一般来说,需要按地图值对地图条目进行排序是非典型的。


关于 的注释==Integer

您的原始比较器使用 进行比较。这几乎总是错误的,因为操作数是参考相等,而不是值相等。Integer====Integer

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

相关问题


答案 2

多基因神经质的答案几乎是完美的。它有一个重要的错误。它不会处理值相同的映射条目。

此代码:...

Map<String, Integer> nonSortedMap = new HashMap<String, Integer>();
nonSortedMap.put("ape", 1);
nonSortedMap.put("pig", 3);
nonSortedMap.put("cow", 1);
nonSortedMap.put("frog", 2);

for (Entry<String, Integer> entry  : entriesSortedByValues(nonSortedMap)) {
    System.out.println(entry.getKey()+":"+entry.getValue());
}

将输出:

ape:1
frog:2
pig:3

请注意,我们的奶牛是如何消失的,因为它与我们的猿共享值“1”:O!

对代码的这种修改解决了这个问题:

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; // Special fix to preserve items with equal values
                }
            }
        );
        sortedEntries.addAll(map.entrySet());
        return sortedEntries;
    }

推荐