1
  • I need an iterable data structure that provides the possibilities of the standard Iterator<> interface (next(), hasNext(), etc.).

  • Additionally it should be possible to reposition the iterator at a certain position.


Is there any class that already provides the mentioned possibilities?


Otherwise I would implement something like the following:

public class PositionableIterator<E> implements Iterator<E> {

  private final List<E> delegate;
  private Iterator<E> iterator;

  public PositionableIterator(List<E> delegate) {
    this.delegate = delegate;
    this.iterator = delegate.iterator();
  }

  public void moveTo(int index) {
    this.iterator = delegate.listIterator(index);
  }

  public void moveTo(E element) {
    this.iterator = delegate.listIterator(delegate.indexOf(element));
  }

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

  @Override
  public E next() {
    return iterator.next();
  }
}

Do you see any drawbacks using this approach?

iamwhoiam
  • 287
  • 1
  • 6
  • 15
JDC
  • 4,247
  • 5
  • 31
  • 74
  • One drawback is that if the ``List`` does not have random access (sequential access, linked list), then it is parsed till the index-th object for every call to ``moveTo``. This is expensive for a large List. ``moveTo(E element)`` is even more costly. – Pradhan May 16 '17 at 17:58

3 Answers3

0

I would suggest just convert iterator to list and use its functionality. Because that way it is easier to understand and maintain. There is example of converting Convert Iterator to ArrayList

Community
  • 1
  • 1
Mikita Herasiutsin
  • 118
  • 1
  • 2
  • 7
0

You can achieve the same by doing the following :

Iterator<String> iterator = input.iterator();
for (; index > 0; --index) {
      iterator.next();       // move the iterator to index
}
Neha Kumari
  • 757
  • 7
  • 16
0

You can also use Google guavas Iterables methods to get an item from a specific position from an Iterable.


Iterator<Something> iterator = repo.GetMyIterator();

Something atPos5 = Iterables.get(iterator, 5);

M. Schett
  • 784
  • 8
  • 8