Java Stream API
过滤、映射、分组、聚合、排序
过滤 + 映射 + 收集
List<String> names = users.stream()
.filter(u -> u.getAge() > 18)
.map(User::getName)
.toList(); // Java 16+
分组
Map<String, List<User>> byCity = users.stream()
.collect(Collectors.groupingBy(User::getCity));
// 分组计数
Map<String, Long> cnt = users.stream()
.collect(Collectors.groupingBy(User::getCity, Collectors.counting()));
聚合
int sum = list.stream().mapToInt(Integer::intValue).sum();
OptionalInt max = list.stream().mapToInt(Integer::intValue).max();
double avg = users.stream().mapToInt(User::getAge).average().orElse(0);
去重与排序
List<String> uniq = list.stream().distinct().toList();
List<User> sorted = users.stream()
.sorted(Comparator.comparing(User::getAge).reversed())
.toList();
匹配
boolean any = users.stream().anyMatch(u -> u.getAge() > 60);
boolean all = users.stream().allMatch(User::isActive);
Optional<User> first = users.stream().filter(...).findFirst();
first.ifPresent(u -> ...); // 避免直接 get() 空指针