InBatchesOfCollector.java

/*
 * Copyright 2020 Collect Utils Authors
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package net.morimekta.collect.collectors;

import net.morimekta.collect.UnmodifiableList;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;

import static net.morimekta.collect.UnmodifiableList.toList;
import static net.morimekta.collect.UnmodifiableSet.setOf;

@SuppressWarnings("JdkObsolete")
public class InBatchesOfCollector<T> implements Collector<T, LinkedList<List<T>>, List<List<T>>> {
    private final int itemsPerBatch;

    public InBatchesOfCollector(int itemsPerBatch) {
        this.itemsPerBatch = itemsPerBatch;
    }

    @Override
    public Supplier<LinkedList<List<T>>> supplier() {
        return LinkedList::new;
    }

    @Override
    public BiConsumer<LinkedList<List<T>>, T> accumulator() {
        return (l, i) -> {
            List<T> last = l.peekLast();
            if (last == null || last.size() >= itemsPerBatch) {
                last = new ArrayList<>(itemsPerBatch);
                l.add(last);
            }
            last.add(i);
        };
    }

    @Override
    public BinaryOperator<LinkedList<List<T>>> combiner() {
        return (a, b) -> {
            // Merge the two lists so the batches matches the order
            // of the non-parallel inBatchesOf with (a1..an) + (b1..bn)
            // as the set of items. It's not extremely efficient, but
            // works fine as this is not optimized for parallel streams.
            List<T> last = a.peekLast();
            while (!b.isEmpty()) {
                for (T i : b.peekFirst()) {
                    if (last == null || last.size() >= itemsPerBatch) {
                        last = new ArrayList<>(itemsPerBatch);
                        a.add(last);
                    }
                    last.add(i);
                }
                b.pollFirst();
            }
            return a;
        };
    }

    @Override
    public Function<LinkedList<List<T>>, List<List<T>>> finisher() {
        return batches -> batches.stream()
                                 .map(UnmodifiableList::asList)
                                 .collect(toList());
    }

    @Override
    public Set<Characteristics> characteristics() {
        return setOf(Characteristics.UNORDERED);
    }
}