0

How can I use a for each loop with a function that returns an iterator in Java? For example, I'd like to use a for-each loop for a function with this signature:

public Iterator<Integer> intIterator();

Is it possible or do I have to use a regular for-loop?

3 Answers 3

4

Unfortunately, Java's for-each is defined to require an Iterable, and Iterators aren't Iterable. This can be a pain if, say, you want to provide 3 kinds of iterator for a tree or forward and backward iterators over a data structure.

The easiest way is to use a regular for loop, but if you want, you can write a wrapper class, like so:

public class IteratorWrapper<E> implements Iterable<E> {
    private Iterator<E> iterator;

    public IteratorWrapper(Iterator<E> iterator) {
        this.iterator = iterator;
    }

    public Iterator<E> iterator() {
        return iterator;
    }

    // Static import the following method for less typing at the
    // call sites.
    public static <E> IteratorWrapper<E> wrapIter(Iterator<E> iterator) {
        return new IteratorWrapper<E>(iterator);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

for-each loop can only iterate over an array or an instance of java.lang.Iterable. you can not do it.

you can iterate like -

Iterator<Integer> iterator = intIterator();
for (; iterator.hasNext();) {
    Integer type =  iterator.next();
}

Comments

0

You cannot directly use the iterator as other people have said.

Make another function :

public Iterable<Integer> intIterable() {
    return new Iterable<Integer>() {
        @Override
        public Iterator<Integer> iterator() {
                    return intIterator();
        }
    }
}

Use in for-each loop like

for ( Integer int : object.intIterable() ) {
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.