Java - Stream - Collect every N elements

后端 未结 6 1281
忘掉有多难
忘掉有多难 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:37

    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]
    

提交回复
热议问题