我想复制Java 8流,以便我可以处理它两次.我可以collect作为一个列表并从中获得新的流;
// doSomething() returns a stream
List<A> thing = doSomething().collect(toList());
thing.stream()... // do stuff
thing.stream()... // do other stuff
Run Code Online (Sandbox Code Playgroud)
但我认为应该有一种更有效/更优雅的方式.
有没有办法复制流而不将其转换为集合?
我实际上正在使用Eithers 流,所以想要在移动到正确的投影之前以一种方式处理左投影并以另一种方式处理.有点像这样(到目前为止,我被迫使用这个toList技巧).
List<Either<Pair<A, Throwable>, A>> results = doSomething().collect(toList());
Stream<Pair<A, Throwable>> failures = results.stream().flatMap(either -> either.left());
failures.forEach(failure -> ... );
Stream<A> successes = results.stream().flatMap(either -> either.right());
successes.forEach(success -> ... );
Run Code Online (Sandbox Code Playgroud)