简体   繁体   中英

Create sorted HashMap from Stream Java 8

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?

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM