比较器,集合和HashMaps

时间:2013-03-29 23:13:06

标签: java hashmap compare

我之前需要按其值对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:

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

你们的任何帮助都将深表感谢,谢谢!

2 个答案:

答案 0 :(得分:1)

您有两种选择:

  1. 更改排序方法以获取Integer而不是Double

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

答案 1 :(得分:1)

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