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);
}
}