File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

For-eaching an iterator

 
Stuart Ash
Ranch Hand
Posts: 637
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The J5 for-each takes an iterable, and collections have been retrofitted to be iterable, thus avoiding the programmer having to extract an iterator.

Now, what if some API gives me only an iterator, is there a way someone can use the for-each loop for its brevity over such an iterator. Any workarounds?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you only have an Iterator (not an Iterable), I don't think there's a way to use it with the "for each" loop.

If you really want to do it, you could write a simple class that implements interface Iterable (not tested and not sure about the generics):
 
Stuart Ash
Ranch Hand
Posts: 637
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jesper,

I tried out your code, with refinements. It works! I'll add this to my personal lib, thanks

 
Ilja Preuss
author
Sheriff
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By the way, this is the Adapter design pattern in action...
 
Stuart Ash
Ranch Hand
Posts: 637
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ilja Preuss:
By the way, this is the Adapter design pattern in action...


Yeah, that's why I named it that way - even though different from Jesper's suggestion.

 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic