2

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

Map<T,List<T>>=
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());
         }};
iniMap=sorted(iniMap,comp);

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.

1 Answer 1

3

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();
       |
       V
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
       |
       V
Comparator<List<T>> c
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.