1

I have the following problem:

I have a Map consisting of String as a key and Object as a value. I want to sort the Map's keys by one of the Object's parameters.

Map<String, Trainer> trainers = new TreeMap<>(); <-- This is my map

The object Trainer has parameters - name and points. I want to sort the Map by who has the most points. How do I do that with the help of Stream API?

ernest_k
  • 44,416
  • 5
  • 53
  • 99
dummydummy
  • 91
  • 1
  • 6
  • 1
    Does this answer your question? [TreeMap sort by value](https://stackoverflow.com/questions/2864840/treemap-sort-by-value) Briefly, you can get collection of `values` from the map and sort them using custom comparator. – Nowhere Man Feb 05 '21 at 16:19
  • Have a look at this: https://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values – Nika Feb 05 '21 at 16:22

1 Answers1

0

You can use that code, for example:

  Map<String, Trainer> source = new HashMap<>();
  source.put("Z", new Trainer("z", 2));
  source.put("B", new Trainer("b", 6));
  source.put("C", new Trainer("c", 1));
  source.put("D", new Trainer("d", 11));

  LinkedHashMap<String, Trainer> result = source.entrySet().stream()
            .sorted(Map.Entry.comparingByValue(Comparator.comparing(Trainer::getPoint)))
            .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (s1, s2) -> s1, LinkedHashMap::new));

Output:

{C=Trainer{name='c', point=1}, Z=Trainer{name='z', point=2}, B=Trainer{name='b', point=6}, D=Trainer{name='d', point=11}}

You have ordered with LinkedHashMap. When you need TreeMap use new TreeMap<>(result);

If you want to compare your Trainer's object by name change the comparator to:

Comparator.comparing(Trainer::getName)

Also you can have more hard comparing by several fields, for example:

Comparator.comparing(Trainer::getPoint).thenComparing(Trainer::getName)
Dmitrii B
  • 2,672
  • 3
  • 5
  • 14