2

I'm trying to sort a Map by it's values using JDK 8 style functions. Though I got the sorting part, I'm not sure how to collect the results in a TreeMap. Can someone explain how to get this done in declarative style?

I need to collect to another Map<String, String>.

    Map<String, String> map = new HashMap<>();
    map.put("John", "time3");
    map.put("Henry", "time6");
    map.put("Smith", "time1");
    map.put("Rock", "time2");
    map.put("Ryan", "time5");
    map.put("Gosling", "time4");

   map.entrySet().stream()
            .sorted(Map.Entry.<String, String>comparingByValue().reversed())
            ;
MFIhsan
  • 1,037
  • 3
  • 15
  • 35
  • Collecting into a `TreeMap` is pointless since it will not preserve the sorted order but will itself sort by the key. You will need to collect into a map that preserves the order of mappings like a `LinkedHashMap`. See [How to sort a LinkedHashMap by value in decreasing order in java stream?](http://stackoverflow.com/q/29860667/3920048). – Misha Oct 05 '15 at 23:09
  • Thanks @misha. I was able to solve it using LinkedHashMap. – MFIhsan Oct 05 '15 at 23:17

1 Answers1

2

Though there were couple of questions similar to this, I explicitly wanted to store the results in a Map. Here is the solution.

    Map<String, String> sortedMap = map.entrySet().stream()
            .sorted(Map.Entry.<String, String>comparingByValue().reversed())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v2, LinkedHashMap::new));
MFIhsan
  • 1,037
  • 3
  • 15
  • 35