本文旨在介绍如何使用 Java Stream API 处理 `Map
有时候,我们需要知道 Map 中所有 List 的最大长度。可以使用 Stream API 简洁地实现:
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
public class Main {
public static int getMaxSize(Map> map) {
return map.values().stream()
.mapToInt(List::size)
.max()
.orElse(0);
}
public static void main(String[] args) {
// 示例数据
Map> data = Map.of(
"car", List.of("toyota", "bmw", "honda"),
"fruit", List.of("apple", "banana"),
"computer", List.of("acer", "asus", "ibm")
);
int maxSize = getMaxSize(data);
System.out.println("Maximum list size: " + maxSize); // 输出:Maximum list size: 3
if (maxSize > 2) {
System.out.println("At least one list has more than 2 elements.");
}
}
} 代码解释:
注意事项:
更常见的需求是筛选出 List 大小超过指定值的键值对,并进行进一步处理。以下代码演示了如何实现:
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static Map> getEntriesLargerThan(Map> map, int size) {
return map.entrySet().stream()
.filter(e -> e.getValue().size() > size)
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue
));
}
public static void main(String[] args) {
// 示例数据
Map> data = Map.of(
"car", List.of("toyota", "bmw", "honda"),
"fruit", List.of("apple", "banana"),
"computer", List.of("acer", "asus", "ibm")
);
Map> filteredMap = getEntriesLargerThan(data, 2);
System.out.println("Entries with list size greater than 2:");
filteredMap.forEach((k, v) -> System.out.println(k + " -> " + v));
}
} 代码解释:
输出结果:
Entries with list size greater than 2: car -> [toyota, bmw, honda] computer -> [acer, asus, ibm]
注意事项:
Map 收集器有多个重载版本,可以处理键冲突等情况。 例如,如果原始 Map 中存在相同的 Key,可以使用 (existingValue, newValue) -> existingValue 来保留旧值,或者使用 (existingValue, newValue) -> newValue 来覆盖旧值。本文介绍了如何使用 Java Stream API 处理 Map