【问题标题】:Sorting a Map by value in Java在 Java 中按值对 Map 进行排序
【发布时间】:2014-04-03 15:15:33
【问题描述】:

我正在尝试对java.util.Map 进行如下排序。

public final class SortMapByValue <K, V extends Comparable<? super V>> implements Comparator<Map.Entry<K, V>>
{
    @Override
    public int compare(Entry<K, V> o1, Entry<K, V> o2) {
        return (o1.getValue()).compareTo(o2.getValue());
    }

    public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValue(Map<K, V> unsortedMap)
    {
        List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(unsortedMap.entrySet());            
        Collections.sort(list);  //Compiler error here.
        Map<K, V> sortedMap = new LinkedHashMap<K, V>();

        for (Map.Entry<K, V> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }
}

如代码中所述,它发出如下编译时错误。

no suitable method found for sort(List<Entry<K,V>>)
    method Collections.<T#1>sort(List<T#1>,Comparator<? super T#1>) is not applicable
      (cannot instantiate from arguments because actual and formal argument lists differ in length)
    method Collections.<T#2>sort(List<T#2>) is not applicable
      (inferred type does not conform to declared bound(s)
        inferred: Entry<K,V>
        bound(s): Comparable<? super Entry<K,V>>)
  where K,V,T#1,T#2 are type-variables:
    K extends Object declared in method <K,V>sortMapByValue(Map<K,V>)
    V extends Comparable<? super V> declared in method <K,V>sortMapByValue(Map<K,V>)
    T#1 extends Object declared in method <T#1>sort(List<T#1>,Comparator<? super T#1>)
    T#2 extends Comparable<? super T#2> declared in method <T#2>sort(List<T#2>)

这也可以在sortMapByValue()方法中按如下方式完成。

Collections.sort(list, new Comparator<Map.Entry<K, V>>()
{
    @Override
    public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
        return (o1.getValue()).compareTo(o2.getValue());
    }
});

但是,相反,我想按照这种方式修复错误(避免使用此匿名比较器)。如何修复该错误?

【问题讨论】:

  • 您有一个ListEntryEntry 类没有实现 Comparable。但是,Collections.sort(..) 需要实现 Comparable 的某种类型的 List
  • 所以你有无法编译的代码和完美运行的代码。有效的代码的问题是你想使用不能编译的代码,而不能编译的代码的问题是你想让它编译。我有这个权利吗?
  • 您需要将比较器传递给Collections.sort,例如像Collections.sort(list, new SortMapByValue());
  • 有可能因为不清楚你在问什么而被关闭,真的吗? :)

标签: java sorting map hashmap


【解决方案1】:

Map.Entry 没有实现Comparable,所以Collections.sort(List&lt;Entry&gt;) 无法知道如何条目应该被排序。所以你必须提供一个比较器。

但由于您的 SortMapByValue 已经实现了 Comparator 接口,您可以简单地使用该类的实例:

Collections.sort(list, new SortMapByValue<>());

另请注意,使用 Java 8 可以显着减少代码长度:

public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValue(Map<K, V> unsortedMap) {
    return unsortedMap.entrySet().stream()
            .sorted(comparing(Entry::getValue))
            .collect(toMap(Entry::getKey, Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多