简体   繁体   中英

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.

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.

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 n th element of an Iterator , but there's nothing built into the JDK.

As a workaround i use this in my utils class

     /**
     * Retrive the 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();
        
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM