Update MappedIterator.java

This commit is contained in:
Andrea Cavalli 2020-08-25 23:37:13 +02:00
parent 3b9dd36025
commit 5317a2ff26

View File

@ -0,0 +1,43 @@
package org.warp.commonutils.functional;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.function.Function;
import org.jetbrains.annotations.Nullable;
public class MappedIterator<A, B> implements Iterator<B> {
private final Iterator<A> iterator;
private final Function<A,B> mappingFunction;
private MappedIterator(Iterator<A> iterator, Function<A, B> mappingFunction) {
this.iterator = iterator;
this.mappingFunction = mappingFunction;
}
public static <T, U> Iterator<U> of(Iterator<T> originalIterator, Function<@Nullable T, @Nullable U> mappingFunction) {
return new MappedIterator<>(originalIterator, mappingFunction);
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public B next() {
return mappingFunction.apply(iterator.next());
}
@Override
public void remove() {
iterator.remove();
}
@Override
public void forEachRemaining(Consumer<? super B> action) {
iterator.forEachRemaining((item) -> {
action.accept(mappingFunction.apply(item));
});
}
}