Stream对集合操作

Stream 的原理:将要处理的元素看做一种流,流在管道中传输,并且可以在管道的节点上处理,包括过滤筛选、去重、排序、聚合等。元素流在管道中经过中间操作的处理,最后由最终操作得到前面处理的结果。
集合有两种方式生成流:

stream() − 为集合创建串行流
parallelStream() - 为集合创建并行流
Stream对集合操作
上图中是 Stream 类的类结构图,里面包含了大部分的中间和终止操作。

中间操作主要有以下方法(此类型方法返回的都是 Stream):map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered
终止操作主要有以下方法:forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator

举例说明

Stream对集合操作
Stream对集合操作
filter(筛选)
private static List testFilter(List students){
return students stream().filter(s ->“浙江”.equals(s.getAddress())).collect(Collectors.toList());}

map(转换)
map 就是将对应的元素按照给定的方法进行转换。
Stream对集合操作
distinct(去重)
Stream对集合操作

引用对象的去重,引用对象要实现hashCode和equal方法,否则去重无效

sorted(排序)
Stream对集合操作
limit(限制返回个数)
Stream对集合操作
skip(删除元素)
集合skip,删除前n个元素
Stream对集合操作
reduce(聚合)
集合reduce,将集合中每个元素聚合成一条数据
Stream对集合操作
运行结果:北京欢迎你
min(求最小值)
Student minS =students stream().min((stu1,stu2)->Integer.compare(stu1.getAge(),stu2.getAge())).get();
anyMatch/allMatch/noneMatch(匹配)
Stream对集合操作