Skip to content

Instantly share code, notes, and snippets.

@remen
Created September 13, 2012 14:35
Show Gist options
  • Save remen/3714697 to your computer and use it in GitHub Desktop.
Save remen/3714697 to your computer and use it in GitHub Desktop.
IteratorWrapper
package com.example;
import java.util.Iterator;
/**
*
* Usage:
* You have a method that returns an iterator (I'm looking at you org.apache.commons.io.FileUtils.lineIterator !!!)
* but you want to use the snazzy for-syntax. Look no further:
*
* import static IteratorWrapper.iterable;
* ...
* for( String line: iterable(iterator) ) {
* System.out.println(line)
* }
*/
public class IteratorWrapper {
public static <E> Iterable<E> iterable(final Iterator<E> iterator) {
return new Iterable<E>() {
boolean hasBeenUsed = false;
public Iterator<E> iterator() {
if( hasBeenUsed ) {
throw new RuntimeException("You can't use this twice, numbnut!");
} else {
hasBeenUsed = true;
return iterator;
}
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment