关于Stream流
Stream流
是一系列元素支持串行和并行聚合操作
- Collection提供了新的
stream()
方法 - 流不存储值,而是通过管道的方式获取值
- 流的本质是函数式的—即对流的操作会生成一个结果,不过并不会修改底层的数据源,集合可以作为流的底层数据源
- 延迟查找—很多流操作(过滤,映射,排序等)都可以延迟实现
与传统迭代器的不同之处
- 和迭代器不同的是,Stream可以并行化操作,而迭代器只能命令式地,串行化操作
- 当使用串行方式去遍历时,每个元素读完后再读下一个元素
- 使用并行去遍历时,数据会被分成多个段,其中每一个都在
不同的线程
中处理,然后将结果一起输出 - Stream的并行操作依赖于
Java7
引入的Fork/Join
框架
1 Stream流的构成
Stream流由三部分构成
- 源
- 零个或多个中间操作
- 终止操作
2 Stream流操作的分类
- 惰性求值—零个或多个操作
- 及早求值—终止操作
3 得到Stream流的三种方式
-
通过流的静态方法
-
通过数组的方式
-
通过集合的方式
-
示例
public class StreamTest {
public static void main(String[] args) {
//1.通过流的静态方法
Stream<String> stream1 = Stream.of("hello", "world", "hello world");
Stream<String> stream2 = Stream.generate(UUID.randomUUID()::toString);
Stream<Integer> stream3 = Stream.iterate(1, item -> item + 2).limit(10);
//2.通过数组的方式
String[] arr = {
"hello", "world", "hello world"};
Stream<String> stream2 = Stream.of(arr);
//3.通过集合的方式
List<String> list = Arrays.asList("hello", "world", "hello world");
Stream<String> stream3 = list.stream();
}
}
4 通过使用流来简化代码
- 举例
public class SteamTest {
public static void main(String[] args) {
//迭代输出1,2,3
IntStream.of(1, 2, 3).forEach(System.out :: println);
System.out.println("+++++");
//输出3,8(不包含8)之间的数
IntStream.range(3, 8).forEach(System.out :: println);
System.out.println("+++++");
//输出3,8(包含8)之间的数
IntStream.rangeClosed(3, 8).forEach(System.out :: println);
System.out.println("+++++");
//将整型list中元素两倍之和
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
System.out.println(list.stream().map(item -> 2 * item).reduce(0, Integer::sum));
}
}
执行结果
1
2
3
+++++
3
4
5
6
7
+++++
3
4
5
6
7
8
+++++
30
5 stream相关接口
5.1 collect
接口
public class StreamTest {
public static void main(String[] args) {
//将Stream转为数组
Stream<String> stream = Stream.of("hello", "world", "hello world");
//其操作结果是将stream中的元素添加到list中
//第一个参数为容器提供者
//第二个参数为累加器
//第三个参数为组合器
List<String> resultList
= stream.collect(() -> new ArrayList<>(),
(list, item) -> list.add(item),
(list1, list2) -> list1.addAll(