eze
eze

Reputation: 2422

How to randomly access data from a Java Iterator

I get an Iterator back from a class and I would like to get the xth element of that iterator. I know I could load it into an ArrayList in a loop or check a counter, but that seems inefficient/ugly. What is the best way to do this?

I thought something like,

List al = new ArrayList(myIterator);
  myval = al.get(6);

But that constructor is undefined. thanks.

Upvotes: 1

Views: 3932

Answers (3)

Paulo Barata
Paulo Barata

Reputation: 1

As a workaround i have this method in my Utilities class

     /**
     * Retrieve the n position object of iterator 
     * @param iterator
     * @param position
     * @return Object at position
     * @throws Exception 
     */
    public static Object iterateTo(Iterator iterator, int position) throws Exception{
        
        if(iterator == null){
            throw new Exception("iterator == null");
        }

        if(position < 0){
            throw new Exception("position < 0");
        }
        
        while(iterator.hasNext() && position > 0){
            position--;
            iterator.next();
        }
        
        if(position != 0){
            throw new Exception("position out of limit");
        }
        
        return iterator.next();
        
    }

so instead of this

{
List al = new ArrayList(myIterator);
  myval = al.get(6);
}

you will have to

{
Object myVal = Utilities.iterateTo(myIterator, 6);
}

Upvotes: 0

Jim Garrison
Jim Garrison

Reputation: 86774

The definition of an Iterator does not allow arbitrary indexing to a position. That's just the way it's defined. If you need that capability you will have to load the data into an indexable collection.

The point of the Iterator interface is to allow sequential access to a collection without knowing anything about its size. Iterators can be forward-only or bi-directional (ListIterator). It's just one specific model for accessing elements of a collection. One advantage is that it implies nothing about the collection size, which could be much too large to fit completely into memory. By allowing only sequential access, the implementation is free to keep only part of the collection in memory at any given moment.

If you need to load the iterator contents into a list you need to do it yourself with a loop.

Upvotes: 9

Louis Wasserman
Louis Wasserman

Reputation: 198471

Nope, you've named the only approaches. You're going to end up needing a for loop to iterate to the appropriate position.

A few utility libraries have shortcuts to load an Iterator's contents into an ArrayList, or to get the nth element of an Iterator, but there's nothing built into the JDK.

Upvotes: 6

Related Questions