Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ListCollectorJvm extends ListCollector {
- static final Set<Collector.Characteristics> CHARACTERLESS = Collections
- .unmodifiableSet(EnumSet.noneOf(Collector.Characteristics.class));
- @Override
- public <T> Collector<T, ?, List<T>> toList() {
- return new CollectorImpl<>((Supplier<SpinyBuffer<T>>) SpinyBuffer::new,
- SpinyBuffer::add, (left, right) -> {
- left.addAll(right);
- return left;
- }, SpinyBuffer::toArrayList, CHARACTERLESS);
- }
- static class SpinyBuffer<T> {
- ConcurrentLinkedQueue<T> queue = new ConcurrentLinkedQueue<>();
- ConcurrentLinkedQueue<SpinyBuffer<T>> buffers = new ConcurrentLinkedQueue<>();
- boolean addedOther = false;
- private AtomicInteger elementSize = new AtomicInteger(0);
- public SpinyBuffer() {
- }
- public void add(T t) {
- if (addedOther) {
- int debug = 3;
- }
- elementSize.incrementAndGet();
- queue.add(t);
- }
- public void addAll(SpinyBuffer<T> other) {
- addedOther = true;
- buffers.add(other);
- }
- int size() {
- return elementSize.get()
- + buffers.stream().mapToInt(SpinyBuffer::size).sum();
- }
- int size = elementSize.get();
- List<T> toArrayList() {
- List<T> result = new ArrayList<>(size());
- addToList(result);
- return result;
- }
- private void addToList(List<T> result) {
- result.addAll(queue);
- for (SpinyBuffer<T> buffer : buffers) {
- buffer.addToList(result);
- }
- }
- }
- /**
- * Simple implementation class for {@code Collector}.
- *
- * @param <T>
- * the type of elements to be collected
- * @param <R>
- * the type of the result
- */
- static class CollectorImpl<T, A, R> implements Collector<T, A, R> {
- private final Supplier<A> supplier;
- private final BiConsumer<A, T> accumulator;
- private final BinaryOperator<A> combiner;
- private final Function<A, R> finisher;
- private final Set<Characteristics> characteristics;
- CollectorImpl(Supplier<A> supplier, BiConsumer<A, T> accumulator,
- BinaryOperator<A> combiner, Function<A, R> finisher,
- Set<Characteristics> characteristics) {
- this.supplier = supplier;
- this.accumulator = accumulator;
- this.combiner = combiner;
- this.finisher = finisher;
- this.characteristics = characteristics;
- }
- @Override
- public BiConsumer<A, T> accumulator() {
- return accumulator;
- }
- @Override
- public Supplier<A> supplier() {
- return supplier;
- }
- @Override
- public BinaryOperator<A> combiner() {
- return combiner;
- }
- @Override
- public Function<A, R> finisher() {
- return finisher;
- }
- @Override
- public Set<Characteristics> characteristics() {
- return characteristics;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement