Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java8 Hashmap sort error [duplicate]

I have a map:

private Map<String, AtomicInteger> keywordMap = new HashMap<String, AtomicInteger>();

I'm trying to sort the Map by value (AtomicInteger), in Java 8, with the following code:

keywordMap
        .entrySet()
        .parallelStream()
        .sorted().forEachOrdered(e -> System.out.print(e.getKey()));

However, I'm getting the following error:

java.lang.ClassCastException: java.util.HashMap$Node cannot be cast to java.lang.Comparable

The error occurs in this line: .forEachOrdered(e -> System.out.print(e.getKey()));

What is wrong with my code?

like image 937
Namjug Avatar asked Jul 28 '26 01:07

Namjug


2 Answers

Try to use:

Stream<Map.Entry<K,V>> keywordMap = keywordMap.entrySet().stream().sorted(Map.Entry.comparingByValue());
like image 172
Rahul Tripathi Avatar answered Jul 30 '26 16:07

Rahul Tripathi


The problem is that you try to use sorted() to sort a stream of Map.Entry instances. Map.Entry does not implement the Comparable interface, and that's why you get the ClassCastException. So you will have to supply a suitable comparator yourself.

Also, AtomicInteger does not implement Comparable, and that is why you cannot use Map.Entry.comparingByValue(). You really have to write your own comparator:

keywordMap.entrySet()
    .parallelStream()
    .sorted((a,b) -> Integer.compare(a.getValue().get(), b.getValue().get())); 

However, AtomicInteger does not implement Comparable for a reason. Typically, AtomicIntegers are accessed by multiple threads and thus they can change during the sorting, which might lead to undesirable results (exceptions, even).

like image 22
Hoopje Avatar answered Jul 30 '26 14:07

Hoopje



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!