Java Stream 流学习笔记
📘 Java Stream 流学习笔记
1. 概念
- Stream 不是集合,而是一种 数据处理工具,用于对集合、数组等数据源进行高效、简洁的操作。
- 设计理念:让数据处理像 SQL 操作一样,链式调用,简洁优雅。
2. 特点
- 一次性使用:流只能消费一次。
- 内部迭代:不用写 for 循环,Stream 自动帮你迭代。
- 惰性求值:中间操作不会立刻执行,直到遇到终止操作。
- 可并行化:支持并行流
parallelStream()
,提高性能。
3. 创建 Stream
// 1. 从集合
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> s1 = list.stream();// 2. 从数组
String[] arr = {"a", "b", "c"};
Stream<String> s2 = Arrays.stream(arr);// 3. 使用 Stream.of
Stream<Integer> s3 = Stream.of(1, 2, 3);// 4. 无限流(需 limit)
Stream<Integer> s4 = Stream.iterate(0, n -> n + 2).limit(5); // 0,2,4,6,8
4. 操作分类
1)中间操作(Intermediate)
返回新的 Stream,可继续链式调用。
常见:
filter()
:过滤map()
:映射(转换)distinct()
:去重sorted()
:排序limit()
:取前 N 个skip()
:跳过前 N 个
2)终止操作(Terminal)
触发流计算,返回结果或副作用。
常见:
forEach()
:遍历collect()
:收集count()
:计数reduce()
:归约anyMatch()
/allMatch()
/noneMatch()
:匹配findFirst()
/findAny()
:查找
5. 常用中间操作示例
list.stream().filter(s -> s.length() > 3) // 过滤.map(String::toUpperCase) // 转大写.distinct() // 去重.sorted(Comparator.comparingInt(String::length)) // 按长度排序.limit(5) // 取前5个.skip(2) // 跳过2个.forEach(System.out::println);
6. 常用终止操作示例
// forEach
list.stream().forEach(System.out::println);// collect
List<String> upper = list.stream().map(String::toUpperCase).collect(Collectors.toList());// count
long cnt = list.stream().count();// reduce (求和)
int sum = Stream.of(1,2,3,4).reduce(0, Integer::sum);// 匹配
boolean hasApple = list.stream().anyMatch(s -> s.equals("apple"));
boolean allLong = list.stream().allMatch(s -> s.length() > 3);
boolean noneEmpty= list.stream().noneMatch(String::isEmpty);// 查找
Optional<String> first = list.stream().findFirst();
7. 方法引用 ::
方法引用是 Lambda 的简写。
方法引用 | 等价 Lambda | 示例 |
---|---|---|
对象::方法 | x -> 对象.方法(x) | list.forEach(System.out::println) |
类::静态方法 | x -> 类.静态方法(x) | map(Integer::parseInt) |
类::实例方法 | x -> x.方法() | map(String::length) |
类::new | x -> new 类(x) | map(Person::new) |
数组::new | n -> new 类型[n] | toArray(String[]::new) |
8. 并行流
list.parallelStream().forEach(System.out::println); // 多线程并行,顺序不保证
适合计算密集型任务,I/O 场景需谨慎。
9. 综合案例
需求:筛选偶数 → 平方 → 排序 → 收集到 List
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);List<Integer> result = numbers.stream().filter(n -> n % 2 == 0) // 过滤偶数.map(n -> n * n) // 平方.sorted() // 排序.collect(Collectors.toList()); // 收集System.out.println(result); // [4, 16, 36, 64, 100]
10. 小结
- Stream 是数据处理工具,不存储数据。
- 中间操作 = 描述数据流向;终止操作 = 执行计算。
- 常配合 Lambda 和方法引用 使用,代码简洁优雅。