Java 8 partition list

后端 未结 5 2225
一个人的身影
一个人的身影 2021-02-18 15:37

Is it possible to partition a List in pure Jdk8 into equal chunks (sublists).

I know it is possible using Guava Lists class, but can we do it with pure Jdk? I don\'t wan

5条回答
  •  后悔当初
    2021-02-18 16:04

    I have tried my own solution with a custom made Collector. I hope someone will find it useful, or help me improve it.

    class PartitioningCollector implements Collector>, List>> {
    
            private final int batchSize;
            private final List batch;
    
            public PartitioningCollector(int batchSize) {
                this.batchSize = batchSize;
                this.batch = new ArrayList<>(batchSize);
            }
    
            @Override
            public Supplier>> supplier() {
                return LinkedList::new;
            }
    
            @Override
            public BiConsumer>, T> accumulator() {
                return (total, element) -> {
                    batch.add(element);
                    if (batch.size() >= batchSize) {
                        total.add(new ArrayList<>(batch));
                        batch.clear();
                    }
                };
            }
    
            @Override
            public BinaryOperator>> combiner() {
                return (left, right) -> {
                    List> result = new ArrayList<>();
                    result.addAll(left);
                    result.addAll(left);
                    return result;
                };
            }
    
            @Override
            public Function>, List>> finisher() {
                return result -> {
                    if (!batch.isEmpty()) {
                        result.add(new ArrayList<>(batch));
                        batch.clear();
                    }
                    return result;
                };
            }
    
            @Override
            public Set characteristics() {
                return emptySet();
            }
        }
    

提交回复
热议问题