Jinnn1 Jinnn1 - 4 months ago 26
Java Question

Sorting Java Map by List values

I need to sort a map by values using sorted method with map and lambda expression as arguments, while map has structure like:

Groovy = [Z, Y, X, D]
Java = [V, B, C, D, A, Z]
C++ = [G, J, H]
C# = [P, S, Q, V, D]
Scala = [A, D]

My sorted method:

sorted(Map<T,List<T>> map,Comparator<Map<T,List<T>>> comp)

and then implement it in another function responsible for reading data from file and putting it into map. This is my sorted method:

public Map<T,List<T>> sorted(Map<T,List<T>> map, Comparator<Map<T,List<T>>> comp){
List list = new LinkedList(map.entrySet());
Collections.sort(list, comp);
HashMap sortedHashMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedHashMap.put(entry.getKey(), entry.getValue());
return sortedHashMap;

And this is how I have used it in another method:

Comparator<Map<T,List<T>>> comp = new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());

When I run my program I get following error:

java.lang.ClassCastException: java.util.LinkedList cannot be cast to java.lang.Comparable

Any help would be appreciated, I am kind of stuck.


Yes, the LinkedList class (as and any List/Collection subclass) doesn't implement the Comparable interface, so you will get the exception at runtime.

(1) You'd better think up your own comparison algorithm with Ts rather than using incorrect casting with Objects:

Comparator<List<T>> comparator = (l1, l2) -> l1.size() - l2.size();

(2) Avoid raw types, try to generalize all code:

HashMap sortedHashMap = new LinkedHashMap();
HashMap<List<T>, T> map = new LinkedHashMap<>();

(3) Turn the anonymous class into a lambda expression.

(4) If you want to sort a map by values (List<T>), the comparator also should be appropriate:

Comparator<Map<T,List<T>>> c
Comparator<List<T>> c