stream数据收集
输出流中的元素
创建测试数据
1 | List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); |
顺序输出
- 使用foreach输出,将里面函数应用每个元素
1 | stream.forEach(System.out::println); |
- 传统迭代器输出
1 | Iterator<Integer> iterator=stream.iterator(); |
- 并行流的情况
1 | list.parallelStream().forEachOrdered(System.out::println); |
并行输出
任意顺序遍历所有元素
1 | list.parallelStream().forEach(System.out::println); |
收集流中的数据
生成指定类型的集合
1 | Integer[] result=stream.toArray(Integer[]::new); |
使用收集器,collect,接受一个collector接口的实例
- 生成常见集合
1 | stream.collect(Collectors.toList()); |
- 指定生成数据结构的类型
1 | stream.collect(Collectors.toCollection(LinkedList::new)); |
- 使用连接操作收集字符串
1 | stream.map(p->p.toString()).collect(Collectors.joining()); |
- 求平均值、总数、和、最大、最小
1 | IntSummaryStatistics statistics=stream.collect(Collectors.summarizingInt(Integer::intValue)); |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.