LulzCop
LulzCop

Reputation: 131

Comparators, Collections, and HashMaps

I earlier needed to sort a HashMap by its values, and I used the comparator with the collections, like so:

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

Now the situation changed, and I needed it to be a HashMap that was sorted. So I changed the code to look like this:

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

and it throws an error, namely 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());

Any help from you guys would be deeply appreciated, thank you!

Upvotes: 1

Views: 832

Answers (2)

Eric
Eric

Reputation: 49

You changed the signature of the sortMap() method from Integer to Double, but are still calling it with Integers. Is using a TreeMap perhaps an option to do implicit sorting?

Upvotes: 1

boomz
boomz

Reputation: 667

You have two choice:

  1. change the sort method to get Integer instead of Double.

  2. change the return type of entry.getValue() to Double!

Upvotes: 1

Related Questions