问题
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 Integer
keys 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