输出流中的元素

创建测试数据

1
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

顺序输出

  • 使用foreach输出,将里面函数应用每个元素
1
stream.forEach(System.out::println);
  • 传统迭代器输出
1
2
3
4
5
Iterator<Integer> iterator=stream.iterator();
while (iterator.hasNext()) {
String name = String.valueOf(iterator.next());
System.out.println(name);
}
  • 并行流的情况
1
list.parallelStream().forEachOrdered(System.out::println);

并行输出

任意顺序遍历所有元素

1
list.parallelStream().forEach(System.out::println);

收集流中的数据

生成指定类型的集合

1
Integer[] result=stream.toArray(Integer[]::new);

使用收集器,collect,接受一个collector接口的实例

  • 生成常见集合
1
2
stream.collect(Collectors.toList());
stream.collect(Collectors.toSet());
  • 指定生成数据结构的类型
1
stream.collect(Collectors.toCollection(LinkedList::new));
  • 使用连接操作收集字符串
1
2
stream.map(p->p.toString()).collect(Collectors.joining());
stream.map(p->p.toString()).collect(Collectors.joining(","));
  • 求平均值、总数、和、最大、最小
1
2
3
4
IntSummaryStatistics statistics=stream.collect(Collectors.summarizingInt(Integer::intValue));
double avg=statistics.getAverage();
long count=statistics.getCount();
long sum=statistics.getSum();