Can you split a stream into two streams?

前端 未结 10 833
栀梦
栀梦 2020-11-27 12:03

I have a data set represented by a Java 8 stream:

Stream stream = ...;

I can see how to filter it to get a random subset - for exa

10条回答
  •  心在旅途
    2020-11-27 12:49

    This is against the general mechanism of Stream. Say you can split Stream S0 to Sa and Sb like you wanted. Performing any terminal operation, say count(), on Sa will necessarily "consume" all elements in S0. Therefore Sb lost its data source.

    Previously, Stream had a tee() method, I think, which duplicate a stream to two. It's removed now.

    Stream has a peek() method though, you might be able to use it to achieve your requirements.

提交回复
热议问题