在 Java 8 中,可以使用 Stream API 和 Lambda 表达式来对 Map<String, List> 按 Key 排序。以下是一个示例代码:

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,以保留插入顺序。

Java 8 Map<String, List<String>> 按 Key 排序

原文地址: https://www.cveoy.top/t/topic/nx0Y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录