我正在尝试将tableProbability
映射排序为一个名为sorted
的新映射。在tableProbability
中,值如下:
键 | |
---|---|
M | 0.1 |
U | 0.3 |
L | 0.3 |
T | 0.2 |
I | 0.1 |
您的代码运行良好,但您可以将其简化如下:
-
来源地图:
LinkedHashMap<Character, Double> tableProbability = new LinkedHashMap<>() {{ put('M', 0.1); put('U', 0.3); put('L', 0.3); put('T', 0.2); put('I', 0.1); }};
System.out.println(tableProbability); // {M=0.1, U=0.3, L=0.3, T=0.2, I=0.1}
-
此代码运行良好:
LinkedHashMap<Character, Double> sorted = new LinkedHashMap<>(); tableProbability.entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .forEachOrdered(x -> sorted.put(x.getKey(), x.getValue()));
System.out.println(sorted); // {U=0.3, L=0.3, T=0.2, M=0.1, I=0.1}
-
简化版:
LinkedHashMap<Character, Double> sorted2 = tableProbability .entrySet().stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .collect(LinkedHashMap::new, (col, e) -> col.put(e.getKey(), e.getValue()), HashMap::putAll);
System.out.println(sorted2); // {U=0.3, L=0.3, T=0.2, M=0.1, I=0.1}
另请参阅:排序映射<字符串,整数>按列表<字符串>使用流
您可能需要这样做。这是常见的操作。如果要返回TreeMap
,可以在下面指定它。通常情况下,一个分配给接口类型。对于TreeMap
,它将是NavigableMap
。
Map<Character, Double> sorted =
tableProbability.entrySet().stream()
.sorted(Map.Entry.comparingByValue(
Comparator.reverseOrder()))
.collect(Collectors.toMap(Entry::getKey,
Entry::getValue,
(a,b)->a, // merge, not used here but
// syntactically required
LinkedHashMap::new // type of map to return
));
使用复合比较器:
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())
.andThen(Map.Entry.comparingByKey())
)