package iterator; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; public class Iterators { public static Iterator subIterator(Iterator it, int fromIndex, int toIndex) { return new Iterator() { // index of the next element in the iterator it int i = 0; @Override public boolean hasNext() { while (i < fromIndex && it.hasNext()) { i++; it.next(); } return i <= toIndex && it.hasNext(); } @Override public E next() { if (!hasNext()) throw new NoSuchElementException(); i++; return it.next(); } public void remove() { if (i < fromIndex + 1) { throw new IllegalStateException(); } it.remove(); } }; } public static void main(String[] args) { for (Iterator it = subIterator(Arrays.asList(0, 1, 2, 3, 4, 5, 6).iterator(), 2, 5); it.hasNext();) System.out.print(it.next() + " "); } }