Create stream of streams from one long stream

前端 未结 4 1926
一向
一向 2020-12-10 15:31

I want to split a single Stream into a Stream of Streams based on the contents of the Streams. The resulting the St

4条回答
  •  长情又很酷
    2020-12-10 16:18

    You may want to implement your own aggregating spliterator to do this. There's already something similar in the proton-pack library (the first link redirects to the one implemented in proton-pack).

    Note that you get a Stream> (you may try to modify the implementation to have a Stream> directly, but you always need to buffer a small amount elements; depending on the window's size; to test whether you should create a new window or not). So for example:

    StreamUtils.aggregate(Stream.of(1, 1, 1, 2, 2, 2, 3, 6, 7, 7, 1, 1), 
                          Objects::equals)
               .forEach(System.out::println);
    

    outputs:

    [1, 1, 1]
    [2, 2, 2]
    [3]
    [6]
    [7, 7]
    [1, 1]
    

提交回复
热议问题