我有一个包含字符串和整数数组的 HashMap,我想按数组的第一个值对映射进行排序。
例如,在条目中:
{"Name1"=[2,4],
"Name2"=[1,5],
"Name3"=[3]}
顺序应该是:
{"Name2"=[1,5],
"Name1"=[2,4],
"Name3"=[3]}
最佳答案
I want to sort the map by the first value of the array
我们可以在从 Map.entrySet()
中提取的流中使用自定义比较器,该比较器会考虑 Map 值中数组的第一个元素进行比较时:
Map<String, Integer[]> map = new HashMap<>();
map.put("Name1", new Integer[]{2,5});
map.put("Name2", new Integer[]{1,4});
map.put("Name3", new Integer[]{3});
Map<String, Integer[]> sorted = map
.entrySet().stream()
.sorted(Comparator.comparing(ent -> ent.getValue()[0]))
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(a, b) -> b,
LinkedHashMap::new));
sorted.forEach((k,v) -> System.out.println("{ " + k + " " + Arrays.toString(v) + " }"));
输出:
{ Name2 [1, 4] }
{ Name1 [2, 5] }
{ Name3 [3] }
关于java - 如何对 HashMap<String, Integer[]> 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57550859/