java8 将MapString ListString按key排序
在Java8中,可以使用Stream API和Lambda表达式来对Map<String, List
Map<String, List<String>> map = new HashMap<>();
map.put("b", Arrays.asList("b1", "b2"));
map.put("a", Arrays.asList("a1", "a2"));
map.put("c", Arrays.asList("c1", "c2"));
// 按key排序
Map<String, List<String>> sortedMap = map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
// 输出排序后的Map
sortedMap.forEach((key, value) -> System.out.println(key + ": " + value));
输出结果为:
a: [a1, a2]
b: [b1, b2]
c: [c1, c2]
在上面的代码中,首先使用entrySet()方法将Map转换为一个Set,然后使用Stream对其进行排序,使用comparingByKey()方法指定按key排序,最后使用toMap()方法将排序后的结果转换为一个新的Map,其中LinkedHashMap::new参数指定返回一个LinkedHashMap,以保留插入顺序
原文地址: http://www.cveoy.top/t/topic/cEI5 著作权归作者所有。请勿转载和采集!