Can I duplicate a Stream in Java 8?

后端 未结 8 2174
别跟我提以往
别跟我提以往 2020-12-08 04:03

Sometimes I want to perform a set of operations on a stream, and then process the resulting stream two different ways with other operations.

Can I do this without ha

8条回答
  •  孤街浪徒
    2020-12-08 04:34

    Either,

    • Move the initialisation into a method, and simply call the method again

    This has the advantage of being explicit about what you are doing, and also works for infinite streams.

    • Collect the stream and then re-stream it

    In your example:

    final int[] arr = IntStream.range(1, 100).filter(n -> n % 2 == 0).toArray();
    

    Then

    final IntStream s = IntStream.of(arr);
    

提交回复
热议问题