Reputation: 3325
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?
Upvotes: 0
Views: 218
Reputation: 280227
Unfortunately, Java's for-each is defined to require an Iterable
, and Iterator
s 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);
}
}
Upvotes: 4
Reputation: 3316
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() ) {
}
Upvotes: 0
Reputation: 41200
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();
}
Upvotes: 0