Stream
Stream流
Stream流是根据数据源(集合,数组)所产生的元素序列
注意:
1.流本身不能存储数据
2.流不能修改数据源中的数据
3.流是一次性的流,流式操作的每一步都会返回一个持有结果的新流
4.延迟执行/惰性加载 : 当不进行终止行为时候,不会执行流式中间操作
关于应用在Stream流上的操作,可以分成两种:Intermediate(中间操作)和Terminal(终止操作)。中间操作的返回结果都是Stream,故可以多个中间操作叠加;终止操作用于返回我们最终需要的数据,只能有一个终止操作。
Stream流操作过程:
1.获取|创建stream
List<Integer> list = new ArrayList<>();
//顺序流
Stream<Integer> stream = list.stream();
//并行流
Stream<Integer> stream2 = list.parallelStream();
2.流式中间操作
筛选和切片
filter(Predicate)将结果为false的元素过滤掉
Stream<Employee> stream1 = stream
.filter(e->{
return e.getAge()>=18;
});
limit截断流,使其元素不超过给定数量
Stream<Employee> stream1 = stream.limit(3);
skip跳过元素,返回一个扔掉了前n个元素的流,若流中元素不足n个,则返回一个空流。
Stream<Employee> stream1 = stream.skip(1);
distinct去重,通过流所生产元素的hashCode()和equals()去除重复元素
Stream<Employee> stream1 = stream.distinct();
3.终止行为(返回的结果不在是stream)
简单操作
- max(Comparator)
- min(Comparator)
- count()
- findFirst()
返回第一个元素 - findAny()
返回任意元素
收集操作 collect()
Stream<Employee> stream1 = stream
.filter(e->{
return e.getAge()>=18;
})
.distinct()
.limit(3)
.skip(1)
.collect(Collectors.toList());