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

com.github.basking2.sdsai.itrex.iterators.MappingIterator Maven / Gradle / Ivy

There is a newer version: 1.1.23
Show newest version
package com.github.basking2.sdsai.itrex.iterators;

import com.github.basking2.sdsai.itrex.SExprRuntimeException;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * An iterator that wraps another {@link Iterator} and maps its output values to values this returns.
 *
 * Any {@link Exception} thrown during the mapping results in a {@link NoSuchElementException} being thrown
 * from this class's {@link #next()} method.
 */
public class MappingIterator implements Iterator {

    private Iterator iterator;
    private Mapper f;

    public MappingIterator(final Iterator iterator, final Mapper f) {
        this.iterator = iterator;
        this.f = f;
    }

    public void setMapping(Mapper f) {
        this.f = f;
    }

    @Override
    public boolean hasNext() {
        return iterator.hasNext();
    }

    @Override
    public R next() {
        try {
            return f.map(iterator.next());
        }
        catch (final NoSuchElementException e) {
            throw e;
        }
        catch (final Throwable e) {
            throw new SExprRuntimeException(e.getMessage());
        }
    }

    @FunctionalInterface
    public interface Mapper {
        R map(T r) throws Exception;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy