Suraj Prasad
Suraj Prasad

Reputation: 251

Error while sorting using Collections sort

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

Upvotes: 1

Views: 361

Answers (3)

Ankit Sharma
Ankit Sharma

Reputation: 1654

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());

Upvotes: 0

Vikas
Vikas

Reputation: 7175

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

Upvotes: 2

Hưng Chu
Hưng Chu

Reputation: 1052

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

Upvotes: 2

Related Questions