猿问

如何对 HashMap<String, Integer[]> 进行排序?

我有一个带有字符串和整数数组的 HashMap,我想按数组的第一个值对映射进行排序。


例如,在条目中:


{"Name1"=[2,4],

 "Name2"=[1,5],

 "Name3"=[3]}

顺序应该是:


{"Name2"=[1,5],

 "Name1"=[2,4],

 "Name3"=[3]}


萧十郎
浏览 87回答 1
1回答

神不在的星期二

我想按数组的第一个值对地图进行排序我们可以在从 中提取的流中使用自定义比较器,在进行比较时Map.entrySet()考虑Map 值中数组的第一个元素:&nbsp;Map<String, Integer[]> map = new HashMap<>();&nbsp;map.put("Name1", new Integer[]{2,5});&nbsp;map.put("Name2", new Integer[]{1,4});&nbsp;map.put("Name3", new Integer[]{3});&nbsp;Map<String, Integer[]> sorted = map&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.entrySet().stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.sorted(Comparator.comparing(ent -> ent.getValue()[0]))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toMap(Map.Entry::getKey,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Map.Entry::getValue,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (a, b) -> b,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;LinkedHashMap::new));&nbsp;sorted.forEach((k,v) -> System.out.println("{ " + k + " " + Arrays.toString(v) + " }"));输出:{ Name2 [1, 4] }{ Name1 [2, 5] }{ Name3 [3] }
随时随地看视频慕课网APP

相关分类

Java
我要回答