All Downloads are FREE. Search and download functionalities are using the official Maven repository.

nl.vpro.util.BasicWrappedIterator Maven / Gradle / Ivy

There is a newer version: 5.3.1
Show newest version
package nl.vpro.util;

import java.util.Collection;
import java.util.Iterator;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;

import org.checkerframework.checker.nullness.qual.NonNull;

/**
 * @author Michiel Meeuwissen
 * @since 0.31
 */
public class BasicWrappedIterator extends WrappedIterator {

    private final Supplier size;
    private final Supplier totalSize;

    private long count = 0;

    public BasicWrappedIterator(Iterator wrapped) {
        super(wrapped);
        size = null;
        totalSize = null;
    }

    @lombok.Builder(builderClassName = "Builder")
    protected BasicWrappedIterator(
        Supplier sizeSupplier,
        Supplier totalSizeSupplier,
        Long size,
        Long totalSize,
        Iterator wrapped) {
        super(wrapped);
        this.size = sizeSupplier != null ? sizeSupplier : () -> size;
        this.totalSize = totalSizeSupplier != null ? totalSizeSupplier :  () -> totalSize;
    }


    public BasicWrappedIterator(Long size, Long totalSize, Iterator wrapped) {
        this(null, null, size, totalSize, wrapped);
    }

    public BasicWrappedIterator(AtomicLong size, AtomicLong totalSize, Iterator wrapped) {
        this(size::get, totalSize::get, null, null, wrapped);
    }

    public BasicWrappedIterator(Long totalSize, Iterator wrapped) {
        this(totalSize, totalSize, wrapped);
    }

    public BasicWrappedIterator(AtomicLong totalSize, Iterator wrapped) {
        this(totalSize, totalSize, wrapped);
    }

    public BasicWrappedIterator(Collection wrapped) {
        super(wrapped.iterator());
        this.size = () -> (long) wrapped.size();
        this.totalSize = () -> (long) wrapped.size();
    }

    @Override
    public @NonNull Optional getSize() {
        if (size != null) {
            return Optional.ofNullable(size.get());
        } else {
            return super.getSize();
        }
    }

    @Override
    public @NonNull Optional getTotalSize() {
        if (totalSize != null) {
            return Optional.ofNullable(totalSize.get());
        } else {
            return super.getTotalSize();
        }
    }

    @Override
    public T next() {
        T n = wrapped.next();
        count++;
        return n;
    }

    @Override
    public Long getCount() {
        return count;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy