Stream API是一个强大的工具,用于处理数据集合。它提供了一种声明式的方式来处理数据,支持并行处理,使代码更加简洁和高效。
1. 基本概念
Stream API提供了一种高效且易于使用的处理数据的方式。它不是数据结构,而是对集合对象功能的增强,专注于对集合对象进行各种非常便利、高效的聚合操作或大批量数据操作。
2. 创建Stream的方式
- 从集合创建:list.stream()
- 从数组创建:Arrays.stream(array)
- 从静态方法创建:Stream.of(), Stream.iterate(), Stream.generate()
3. Stream操作类型
Stream操作分为中间操作和终端操作:
中间操作:返回Stream本身,可以链式调用(如filter、map、sorted等)
终端操作:返回特定类型的结果(如collect、forEach、count、reduce等)
4.操作
fiter
用于过滤元素,接收一个Predicate函数式接口作为参数:
List<String> filtered = list.stream()
.filter(s -> s.startsWith("a"))
.collect(Collectors.toList());
map
用于转换元素,接收一个Function函数式接口作为参数:
List<Integer> lengths = list.stream()
.map(String::length)
.collect(Collectors.toList());
collect
终端操作,用于收集Stream中的元素到集合中:
// 收集到List中
List<String> result = stream.collect(Collectors.toList());
// 收集到Set中
Set<String> result = stream.collect(Collectors.toSet());
// 收集到Map中
Map<String, Integer> result = stream.collect(Collectors.toMap(
String::toUpperCase,
String::length
));
groupingBy
用于分组操作,常用于Collectors中:
Map<String, List<Person>> peopleByCity = people.stream()
.collect(Collectors.groupingBy(Person::getCity));
5. 其他重要操作
- distinct(): 去除重复元素
- sorted(): 排序
- limit(): 限制元素数量
- skip(): 跳过元素
- forEach(): 遍历
- reduce(): 归约操作
- count(): 计数
6. 并行流
Stream API支持并行处理,可以大大提高大数据集的处理效率:
XML
list.parallelStream()
.filter(s -> s.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());
7. 函数式接口
Stream API大量使用了函数式接口:
- Predicate<T>: 布尔值判断
- Function<T,R>: 转换函数
- Consumer<T>: 消费数据
- Supplier<T>: 提供数据
8. 实际应用示例
XML
// 提取站点名称并去重
Set<String> siteNames = codeInfoExceDTOS.stream()
.map(PsSourceCodeInfoExceDTO::getSiteName)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
// 按出库单号分组
Map<String, List<PsSourceCodeInfoExceDTO>> groupedByOutNum = codeInfoExceDTOS.stream()
.collect(Collectors.groupingBy(PsSourceCodeInfoExceDTO::getOutNum));