1

When running the below code I get an error. I need suggestion on how to solve the error.

Map<String, String> map = new HashMap<String, String>();

map.put("test", "milan");
map.put("joo", "arsenal");
map.put("keer", "manu");

List list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator() {

    @Override
    public int compare(Object o1, Object o2) {
        return (((Comparable) ((Map.Entry) (o1)).getValue()).compareTo((Map.Entry) (o2)));
    }
});

Error: Exception in thread "main" java.lang.ClassCastException: java.util.HashMap$Node cannot be cast to java.lang.String

3 Answers 3

2

You are comparing String with Map.Entry in comapre Use ((Map.Entry) (o2)).getValue()),

Collections.sort(list, new Comparator() {

    @Override
    public int compare(Object o1, Object o2) {

        return (((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue()));

    }
});

You can make your code more readable as,

List<Map.Entry<String, String>> list = new LinkedList(map.entrySet());
Collections.sort(list, Comparator.comparing(Map.Entry::getValue));
Sign up to request clarification or add additional context in comments.

Comments

2

In your Comparator return line, it should be:

return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo((Comparable) ((Map.Entry) (o2)).getValue());

The reason is you forgot to get Value from o2

Comments

0

Instead of Collections.sort() you should use list.sort() for sorting a list.

List<Map.Entry<String, String>> list = new LinkedList<>(map.entrySet());
list.sort(Map.Entry.comparingByValue());

1 Comment

Why? How does this fix the issue? You could literally do the same with Collections.sort(list, Map.Entry.comparingByValue()), in fact list.sort(...) is nothing more than a plain redirect.

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.