作者:诺vs诺197 | 来源:互联网 | 2023-06-05 11:18
有时我想使用 Java 流对每个元素运行一个操作,如下所示:List.of("a", "b", "c") .stream() .peek(System.out::println)
有时我想使用 Java 流对每个元素运行一个操作,如下所示:
List.of("a", "b", "c")
.stream()
.peek(System.out::println)
.collect(Collectors.toList());
如您所见,我只想打印每个元素,不需要将结果收集到列表中。但是如果我删除最后一行,则根本不会执行流。所以我的问题是,是否可以在不收集结果的情况下运行流?像run()
什么?
回答
只需使用forEach
循环如下:
List.of("a", "b", "c")
.stream()
.forEach(System.out::println);
Assuming that the OP is simply going to consume the stream, the function could be `x -> {}`.