入门
Java Stream,一个号称可以极大提升程序员开发效率的神器, 一个学会了都不想写for循环的好东西。
本质上是一种函数式编程思维,是将要处理的元素集合看作一种流, 流在管道中传输,进行各种操作。
这是官网给出的Stream的特性:
Sequence of elements − A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes elements on demand. It never stores the elements.
Source − Stream takes Collections, Arrays, or I/O resources as input source.
Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on.
Pipelining − Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream.
Automatic iterations − Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required.
概念
中间操作
(intermediate operation)
调用中间操作只会生成一个标记了该操作的新stream,可以继续执行
中间操作主要包括有:
- concat()
- distinct()
- filter()
- flatMap()
- limit()
- map()
- peek()
- skip()
- sorted()
- parallel()
- sequential()
- unordered()
最终操作
(terminal operation)
元素流在管道中经过中间操作的处理,最后由最终操作得到前面处理的结果。
最终操作主要有:
- allMatch()
- anyMatch()
- collect()
- count()
- findAny()
- findFirst()
- forEach()
- forEachOrdered()
- max()
- min()
- noneMatch()
- reduce()
- toArray()
使用举例
查找最大最小值
List<T> list = new LinkedList<>();
...
//最小值
Optional<T> min =
list.stream()
.min(Comparator.comparing(T::getScore));
if(min.isPresent()){
T tMin = min.get();
}
//最大值
Optional<T> max =
list.stream()
.max(Comparator.comparing(T::getScore));
if(max.isPresent()){
T tMax = t.get();
}
遍历打印
List<T> list = new LinkedList<>();
...
list.stream()
.forEach(
i ->System.out.println(i));
分页
List<T> list = new LinkedList<>();
...
List<T> pagedList = list.stream()
.skip(offset)
.limit(limit)
.collect(Collectors.toList());
List 转 Map
下标index为key
List<T> list = new LinkedList<>();
Map<Long, Integer> map = IntStream.range(0, list.size())
.boxed()
.collect(Collectors.toMap(i -> i,i -> list.get(i), (p1,p2)->p1));
提取List中某字段
List<T> list = new LinkedList<>();
...
List<Integer> newList = list.stream()
.map(T::getField)
.collect(Collectors.toList());
List<List> to List
List<List<T>> list = new LinkedList<>();
...
List<Long> collectIds = list.stream()
.flatMap(List::stream)
.collect(Collectors.toList());