🚀 Java Stream 流式操作实战示例
1. 基础示例:过滤、映射、收集
List<String> fruits = List.of("apple", "banana", "cherry", "avocado");List<String> result = fruits.stream().filter(f -> f.startsWith("a")) .map(String::toUpperCase) .toList(); System.out.println(result);
2. Map 流式操作:找出成绩优秀的同学
Map<String, Integer> scores = Map.of("Tom", 90, "Jerry", 80, "Anna", 95);List<String> topStudents = scores.entrySet().stream().filter(e -> e.getValue() > 85) .map(Map.Entry::getKey) .toList();System.out.println(topStudents);
3. 排序与去重
List<Integer> numbers = List.of(5, 3, 9, 1, 3, 5);List<Integer> result = numbers.stream().distinct() .sorted() .toList();System.out.println(result);
4. 聚合计算:reduce
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
int sum = numbers.stream().reduce(0, Integer::sum);System.out.println(sum);
5. 分组统计:groupingBy
List<String> words = List.of("apple", "ant", "banana", "bat", "cherry");Map<Character, List<String>> grouped = words.stream().collect(Collectors.groupingBy(w -> w.charAt(0))); System.out.println(grouped);
6. 统计操作
List<Integer> numbers = List.of(10, 20, 30, 40);IntSummaryStatistics stats = numbers.stream().mapToInt(Integer::intValue).summaryStatistics();System.out.println(stats.getCount());
System.out.println(stats.getSum());
System.out.println(stats.getAverage());
7. 扁平化 flatMap
List<List<String>> nested = List.of(List.of("a", "b"),List.of("c", "d", "e")
);List<String> flat = nested.stream().flatMap(List::stream) .toList();System.out.println(flat);
8. 文件流式处理(行处理)
try (Stream<String> lines = Files.lines(Path.of("data.txt"))) {long count = lines.filter(line -> line.contains("error")).count();System.out.println("包含 error 的行数: " + count);
} catch (IOException e) {e.printStackTrace();
}
9. 无限流:生成数据流
List<Integer> first10Even = Stream.iterate(0, n -> n + 2) .limit(10) .toList();System.out.println(first10Even);
10. 并行流:加速处理大集合
List<Integer> numbers = IntStream.range(1, 1_000_000).boxed().toList();long count = numbers.parallelStream() .filter(n -> n % 2 == 0).count();System.out.println("偶数个数: " + count);
✨ 总结
- 集合流:
stream()
,常用 filter/map/sorted/distinct
- Map流:从
entrySet()/keySet()/values()
开始 - 聚合统计:
reduce
、Collectors.groupingBy
、summaryStatistics
- 文件流:
Files.lines()
,边读边处理,避免内存爆炸 - 无限流:
Stream.iterate/generate
,适合模拟数据流 - 并行流:
parallelStream()
,多核加速大数据处理