blueprint.sdk.util.IndexingIterator Maven / Gradle / Ivy
/*
License:
blueprint-sdk is licensed under the terms of Eclipse Public License(EPL) v1.0
(http://www.eclipse.org/legal/epl-v10.html)
Distribution:
Maven Central - https://search.maven.org/artifact/io.github.lempel/blueprint-sdk
MVN Repository - https://mvnrepository.com/artifact/io.github.lempel/blueprint-sdk
*/
package blueprint.sdk.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.BiConsumer;
/**
* Iterator with index
*
* @author [email protected]
* @since 2016. 11. 22
*/
public class IndexingIterator implements Iterator {
private Iterator iterator;
private int index = -1;
public IndexingIterator(Iterable iterble) {
this.iterator = iterble.iterator();
}
public IndexingIterator(Iterator iterator) {
this.iterator = iterator;
}
public IndexingIterator wrap(Iterable iterable) {
return new IndexingIterator(iterable);
}
public IndexingIterator wrap(Iterator iterator) {
return new IndexingIterator(iterator);
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public E next() {
E result;
try {
result = iterator.next();
index++;
} catch (NoSuchElementException e) {
throw e;
}
return result;
}
/**
* @return current index
*/
public int index() {
return index;
}
public void forEach(BiConsumer action) {
Objects.requireNonNull(action);
while (hasNext()) {
E item = next();
action.accept(index(), item);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy