java - 在 Java 中按值对 Map 进行排序

标签 java sorting map hashmap

我正在尝试按如下方式对 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());
    }
});

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

最佳答案

Map.Entry不执行 Comparable , 所以 Collections.sort(List<Entry>)无法知道条目应该如何排序。所以你必须提供一个比较器。

但是自从你的 SortMapByValue已经实现了 Comparator 接口(interface),您可以简单地使用该类的实例:

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

关于java - 在 Java 中按值对 Map 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22132103/

相关文章:

algorithm - 将整数数组拆分为尽可能多的具有相同总和的子数组

excel - 将整个工作表排序到最后一行

iphone - 核心数据通过两个描述符对数据进行排序

c++ - STL 映射与静态数组

java - 如何手动查找android文件的文件路径?

javax.jms.MessageListener : What additional threading concerns to take care of?

map - GNUPLOT:来自一组点的二维直方图

android - 选项卡上的 SupportMapFragment。我只能看到一次

java - 如何在paint()方法之外的小程序中打印

java - SQL 异常 : Too many database connection