Sorting HashMap String values using Java 8 Stream doesn't work [duplicate]

最后都变了- 提交于 2019-12-11 06:09:06

问题


I'm using the solution from this question to sort the String values in a LinkedHashMap. However the sorting simply doesn't work. Here is the code I wrote.

Map<Integer, String> sortedMap = myMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry<Integer, String>::getKey, 
                    Map.Entry<Integer, String>::getValue));

myMap = new LinkedHashMap<Integer, String>(sortedMap);

The weird thing is that it is sorting the Integerkeys when both comparingByValue and comparingByKey methods are used. So it definitely is sorting, just not the String values but in both cases the Integer keys. I don't understand what I'm doing wrong here.


回答1:


The toMap collector you are using put the elements in an HashMap, so sorting does not help here since you end up putting them in a non-ordered collection.

Use the overloaded toMap method, and supply a LinkedHashMap as concrete instance, i.e:

Map<Integer, String> sortedMap = 
     myMap.entrySet()
          .stream()
          .sorted(Map.Entry.comparingByValue())
          .collect(Collectors.toMap(Map.Entry::getKey,
                                    Map.Entry::getValue, 
                                    (a, b) -> a, //or throw an exception
                                    LinkedHashMap::new));



回答2:


My guess would be that Collectors.toMap is collecting them in an unordered map, immediately destroying the ordering.

Try collecting them directly in a LinkedHashMap:

LinkedHashMap<Integer, String> newMap = new LinkedHashMap<>();
Map<Integer, String> sortedMap = myMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .collect((k, v) -> newMap.put(k, v));
myMap = newMap;

As for why the integer keys are sorted: this is probably mere coincidence, based on how the HashMap is bucketing the keys.



来源:https://stackoverflow.com/questions/37591675/sorting-hashmap-string-values-using-java-8-stream-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!