Search code examples
javasortinghashmap

How to sort by key in hashmap of objects without overriding compareTo?


I have this HashMap Map<Person, List<Information>>. How can I sort this map in reversed order by the double attribute in class Person?

I tried this:

origin.entrySet().stream()
        .sorted(Comparator.comparingDouble(k -> k.getKey().getScore())
        .collect(
            Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (oldValue, newValue) -> oldValue,
                LinkedHashMap::new));

It works, but since I use the function .reversed at the end of getScore() then getKey() returns error. Cannot resolve method 'getKey' in 'Object

Class Person:

public class Person{
double score;
Information information;

}

Solution

  • An easy way to work around that issue is to move the Comparator outside of your stream pipeline:

    Comparator<Entry<Person,List<Information>>> byScore = Comparator.comparingDouble(k -> k.getKey().getScore());
        origin.entrySet().stream()
        .sorted(byScore.reversed())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new));
    

    or provide an explicit parameter type in the lambda:

    origin.entrySet().stream()
        .sorted((Comparator.comparingDouble((Entry<Person,List<Information>> k) -> k.getKey().getScore())).reversed())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new));