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
You can create your own Collector. The easiest way is to call Collector.of().
Since your use case requires values to be processed in order, here is an implementation that simply doesn't support parallel processing.
public static Collector>, List>> blockCollector(int blockSize) {
return Collector.of(
ArrayList>::new,
(list, value) -> {
List block = (list.isEmpty() ? null : list.get(list.size() - 1));
if (block == null || block.size() == blockSize)
list.add(block = new ArrayList<>(blockSize));
block.add(value);
},
(r1, r2) -> { throw new UnsupportedOperationException("Parallel processing not supported"); }
);
}
Test
List input = Arrays.asList("a","b","c","d","e","f","g","h","i","j");
List> output = input.stream().collect(blockCollector(3));
output.forEach(System.out::println);
Output
[a, b, c]
[d, e, f]
[g, h, i]
[j]