2

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;

}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Refer this thread https://www.java67.com/2017/07/how-to-sort-map-by-values-in-java-8.html – Rupesh Jun 12 '20 at 12:17
  • See this related post [comparator-reversed-does-not-compile-using-lambda](https://stackoverflow.com/questions/25172595/comparator-reversed-does-not-compile-using-lambda) – Eritrean Jun 12 '20 at 12:22

1 Answers1

1

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));
Eritrean
  • 15,851
  • 3
  • 22
  • 28
  • both of them does not work, the first one returns `Cannot resolve symbol 'byScore'` and the second : Type 'ap.parser.ApInput.Absyn.Entry' does not have type parameters –  Jun 12 '20 at 12:26
  • You need to import `import java.util.Map.Entry;` – Eritrean Jun 12 '20 at 12:29