1

我之前需要按其值对 HashMap 进行排序,并且我将比较器与集合一起使用,如下所示:

private LinkedHashMap<String, Integer> sortMap(Map<String, Integer> results, int count)
{
    List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(results.entrySet());

    Comparator<Entry<String, Integer>> comparator = new Comparator<Entry<String, Integer>>() {
        @Override
        public int compare(Entry<String, Integer> a, Entry<String, Integer> b) {
            return b.getValue().compareTo(a.getValue());
        }
    };

    Collections.sort(entries, comparator);

    LinkedHashMap<String, Integer> sorted = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : entries)
        sorted.put(entry.getKey(), entry.getValue());

    return sorted;
}

现在情况发生了变化,我需要它是一个经过排序的 HashMap。所以我将代码更改为如下所示:

private LinkedHashMap<String, Double> sortMap(Map<String, Double> results, int count)
{
    List<Map.Entry<String, Double>> entries = new ArrayList<Map.Entry<String, Double>>(results.entrySet());

    Comparator<Entry<String, Double>> comparator = new Comparator<Entry<String, Double>>() {
        @Override
        public int compare(Entry<String, Double> a, Entry<String, Double> b) {
            return b.getValue().compareTo(a.getValue());
        }
    };

    Collections.sort(entries, comparator);

    LinkedHashMap<String, Double> sorted = new LinkedHashMap<String, Double>();
    for (Entry<String, Double> entry : entries)
        sorted.put(entry.getKey(), entry.getValue());

    return sorted;
}

它抛出一个错误,即java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double在:

    at myPackage.myClass$1.compare(myClass.java:124)
    at myPackage.myClass$1.compare(myClass.java:1)
    at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
    at java.util.TimSort.sort(Unknown Source)
    at java.util.TimSort.sort(Unknown Source)
    at java.util.Arrays.sort(Unknown Source)
    at java.util.Collections.sort(Unknown Source)
    at myPackage.myClass.sortMap(myClass.java:128)

myClass.java.128 :Collections.sort(entries, comparator);
myClass.java.124 :return b.getValue().compareTo(a.getValue());

你们的任何帮助将不胜感激,谢谢!

4

2 回答 2

1

您将 sortMap() 方法的签名从 Integer 更改为 Double,但仍使用 Integers 调用它。使用 TreeMap 可能是进行隐式排序的一种选择吗?

于 2013-03-30T00:25:35.490 回答
1

你有两个选择:

  1. 将排序方法更改为 getInteger而不是Double.

  2. 将返回类型更改entry.getValue()为 Double!

于 2013-03-29T23:31:50.140 回答