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

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

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

import lombok.ToString;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.BiFunction;

/**
 * A wrapping iterator with the option to skip certain entries (based on comparing with the previous entry)
 * @author Michiel Meeuwissen
 * @since 1.68
 */
@ToString
public class SkippingIterator implements Iterator {

    private final Iterator wrapped;

    private final BiFunction comparator;

    private Boolean hasNext = null;

    private T next;

    @lombok.Builder(builderClassName = "Builder")
    public SkippingIterator(
        Iterator wrapped,
        BiFunction comparator) {
        this.wrapped = wrapped;
        this.comparator = comparator == null ? Objects::equals : comparator;
    }

    public SkippingIterator(
        Iterator wrapped) {
        this(wrapped, Objects::equals);
    }


    @Override
    public boolean hasNext() {
        findNext();
        return hasNext;
    }

    @Override
    public T next() {
        findNext();
        if (hasNext) {
            hasNext = null;
            return next;
        } else {
            throw new NoSuchElementException();
        }
    }

    protected void findNext() {
        if (hasNext == null) {
            hasNext = false;

            while (wrapped.hasNext()) {
                T n = wrapped.next();
                T previous = next;
                if (comparator.apply(previous, n)) {
                    continue;
                } else {
                    hasNext = true;
                    next = n;
                    break;
                }
            }
        }
    }


}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy