1 回答

TA貢獻(xiàn)1963條經(jīng)驗 獲得超6個贊
我想按數(shù)組的第一個值對地圖進(jìn)行排序
我們可以在從 中提取的流中使用自定義比較器,在進(jìn)行比較時Map.entrySet()考慮Map 值中數(shù)組的第一個元素:
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] }
添加回答
舉報