Reputation: 691
I am converting a HashMap<String, Double>
into a HashMap<String, Double>
where the content is sorted by value. When I print out the following:
Stream<Map.Entry<String, Double>> sorted = map.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).forEach(System.out::println);
the data is printed out in the correct order, sorted by value. However, I don't need to print out the data, I want to collapse the content of this stream into a new HashMap with the new sorted order. I tried a few options, but I seem to be getting back my original, unsorted HashMap when I do this:
return map.entrySet()
.stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()));
How can I modify the stream so that I send back the sorted HashMap?
Upvotes: 1
Views: 141
Reputation: 393811
The collector you used produces a HashMap
by default, and HashMap
doesn't have ordering.
You can use a different collector that would produce a LinkedHashMap
, which preserves insertion order:
return map.entrySet()
.stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.collect(Collectors.toMap(entry -> entry.getKey(),
entry -> entry.getValue(),
(a,b)->a,
LinkedHashMap::new));
Upvotes: 5