FilteredIterable.java

package org.opentrafficsim.road.gtu.perception;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Predicate;

import org.djutils.exceptions.Throw;

/**
 * Returns only those elements that comply with the predicate.
 * <p>
 * Copyright (c) 2013-2026 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
 * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
 * </p>
 * @author Alexander Verbraeck
 * @author Peter Knoppers
 * @author Wouter Schakel
 * @param <T> type
 */
public class FilteredIterable<T> implements Iterable<T>
{

    /** Iterable. */
    private final Iterable<T> iterable;

    /** Predicate. */
    private final Predicate<T> predicate;

    /**
     * Constructor.
     * @param iterable iterable
     * @param predicate predicate for elements that should remain
     */
    public FilteredIterable(final Iterable<T> iterable, final Predicate<T> predicate)
    {
        this.iterable = Throw.whenNull(iterable, "iterable");
        this.predicate = Throw.whenNull(predicate, "predicate");
    }

    @Override
    public Iterator<T> iterator()
    {
        return new Iterator<T>()
        {
            @SuppressWarnings("synthetic-access")
            /** iterator */
            private Iterator<T> it = FilteredIterable.this.iterable.iterator();

            /** net */
            private T next;

            @SuppressWarnings("synthetic-access")
            @Override
            public boolean hasNext()
            {
                if (this.next != null)
                {
                    return true;
                }
                while (this.next == null && this.it.hasNext())
                {
                    T n = this.it.next();
                    if (FilteredIterable.this.predicate.test(n))
                    {
                        this.next = n;
                    }
                }
                return this.next != null;
            }

            @Override
            public T next()
            {
                if (hasNext())
                {
                    T n = this.next;
                    this.next = null;
                    return n;
                }
                throw new NoSuchElementException();
            }
        };
    }

}