Java - Stream - Collect every N elements

后端 未结 6 1303
忘掉有多难
忘掉有多难 2020-12-30 02:38

I am trying to learn java - stream. I am able to do simple iteration / filter / map / collection etc.

When I was kind of trying to collect every 3 elements and print

6条回答
  •  太阳男子
    2020-12-30 03:35

    The most obvious solution:

    IntStream.range(0, list.size() / N)
             .map(i -> i * charactersAmount)
             .mapToObj(i -> list.subList(i, i + charactersAmount)
             .collect(Collectors.toWhateverYouWant());
    

    The first line - you will get a stream of ints from 0 to amount of resulting lines. From your example, list.size() / N equals 4, so stream will be 0-1-2-3.

    The second line - this stream will be mapped to the scaled by the charactersAmount one, in your case it is 3 - 0-3-6-9.

    The third line will cut sublists out of your initial list.

    The last line just treats the resulting stream as collection

提交回复
热议问题