有没有办法在不返回任何内容的情况下运行java流?
有时我想使用 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 -> {}`.