File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes For-eaching an iterator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "For-eaching an iterator" Watch "For-eaching an iterator" New topic
Author

For-eaching an iterator

Stuart Ash
Ranch Hand

Joined: Oct 07, 2005
Posts: 637
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?


ASCII silly question, Get a silly ANSI.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14426
    
  23

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):


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Stuart Ash
Ranch Hand

Joined: Oct 07, 2005
Posts: 637
Hi Jesper,

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

Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
By the way, this is the Adapter design pattern in action...


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Stuart Ash
Ranch Hand

Joined: Oct 07, 2005
Posts: 637
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
 
subject: For-eaching an iterator