1, 概述
-
流式模型
在处理集合/数组元素的时候, 一般我们通过循环遍历才对里面的元素进行处理,例如, 要对一个List<String>集合内的所有元素筛选出长度为3, 以"A"开头的部分, 保存到另一个集合里面去. 用到了循环. JDK8开始, 我们有了一种更简单的处理方式, 就是流式处理. 形象来说,就是把集合和数组的元素放到流水线上一样, 一个元素过来, 依次对其进行各种操作处理.
-
作用
简化集合/数组操作
2, 使用步骤
-
创建流式模型
-
方式1
Collection接口中的default方法将Collection转换为Stream
Collection.stream() --> Stream
-
方式2
Stream接口的静态方法将数组转换为Stream
Stream.of(数组) --> Stream
-
-
对Stream的操作
-
非终结操作
- map
- filter
- limit
- skip
- concat
-
终结操作
- count
- forEach
-
-
Stream转为集合/数组
-
方式1: Stream转换为集合
Stream.collect(Collectors.toList())
Stream.collect(Collectors.toSet())
-
方式2: Stream转换为数组
Stream.toArray()
-