使用Java 8 Stream对HashMap字符串值进行排序不起作用 [英] Sorting HashMap String values using Java 8 Stream doesn't work
问题描述
我正在使用这个问题的解决方案进行排序 LinkedHashMap
中的String值。然而,排序根本不起作用。这是我写的代码。
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);
奇怪的是它正在排序整数
使用 comparisonByValue
和 comparisonByKey
方法时的键。所以它肯定是排序,而不是 String
值,但在两种情况下都是 Integer
键。我不明白我在这里做错了什么。
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.
推荐答案
toMap
您使用的收集器将元素放在 HashMap
中,因此排序对此没有帮助,因为您最终将它们放入非有序集合中。
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.
使用重载的 toMap
方法,并提供 LinkedHashMap
作为具体实例,即:
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));
这篇关于使用Java 8 Stream对HashMap字符串值进行排序不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!