假设我有一个列表,我对其执行多个流操作。
bobs = myList.stream()
.filter(person -> person.getName().equals("Bob"))
.collect(Collectors.toList())
...
和
tonies = myList.stream()
.filter(person -> person.getName().equals("tony"))
.collect(Collectors.toList())
我可以不做吗:
Stream<Person> stream = myList.stream();
这意味着我可以:
bobs = stream.filter(person -> person.getName().equals("Bob"))
.collect(Collectors.toList())
tonies = stream.filter(person -> person.getName().equals("tony"))
.collect(Collectors.toList())
最佳答案
不,你不能。一个 Stream
只能使用一次 当您尝试重用时会抛出以下错误:
java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:229)
根据 Java Docs :
A stream should be operated on (invoking an intermediate or terminal stream operation) only once.
但是您的查询的一个巧妙的解决方案是使用 Stream Supplier。如下所示:
Supplier<Stream<Person>> streamSupplier = myList::stream;
bobs = streamSupplier.get().filter(person -> person.getName().equals("Bob"))
.collect(Collectors.toList())
tonies = streamSupplier.get().filter(person -> person.getName().equals("tony"))
.collect(Collectors.toList())
但同样,每个 get
调用都会返回一个新的流。
关于java-8 - 缓存 Java 8 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51561225/