com.github.basking2.sdsai.itrex.iterators.MappingIterator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sdsai-itrex Show documentation
Show all versions of sdsai-itrex Show documentation
An S-Expression inspiried library focused on iterators.
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