Can I duplicate a Stream in Java 8?

后端 未结 8 2137
别跟我提以往
别跟我提以往 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);
    
    0 讨论(0)
  • 2020-12-08 04:34

    For non-infinite streams, if you have access to the source, its straight forward:

    @Test
    public void testName() throws Exception {
        List<Integer> integers = Arrays.asList(1, 2, 4, 5, 6, 7, 8, 9, 10);
        Stream<Integer> stream1 = integers.stream();
        Stream<Integer> stream2 = integers.stream();
    
        stream1.forEach(System.out::println);
        stream2.forEach(System.out::println);
    }
    

    prints

    1 2 4 5 6 7 8 9 10

    1 2 4 5 6 7 8 9 10

    For your case:

    Stream originalStream = IntStream.range(1, 100).filter(n -> n % 2 == 0)
    
    List<Integer> listOf = originalStream.collect(Collectors.toList())
    
    Stream stream14 = listOf.stream().filter(n -> n % 7 == 0);
    Stream stream10 = listOf.stream().filter(n -> n % 5 == 0);
    

    For performance etc, read someone else's answer ;)

    0 讨论(0)
提交回复
热议问题