Skip to main content

Use foreach to iterate using an Iterator

Posted by forax on September 22, 2006 at 5:09 AM PDT

When the foreach syntax (for(:)) has been
introduced in 1.5, a recurring question was
why foreach is not able to
iterate using an iterator.

I think i have a trick to do that using the
syntax of the closure :

 Iterator<String> scanner=new Scanner(;
for(String word:() { scanner })

Why this code works. The foreach statement needs
an array or an object that implements java.lang.Iterable.
Iterable is an interface that has a single method
iterator that returns an iterator thus the closure
convertion is applicable.


Related Topics >>