Skip to content

Instantly share code, notes, and snippets.

@kjaquier
Last active August 29, 2015 13:57
Show Gist options
  • Save kjaquier/9566940 to your computer and use it in GitHub Desktop.
Save kjaquier/9566940 to your computer and use it in GitHub Desktop.
How to create a simple iterator in Java with just one method.
public class ClosureIterator {
private static interface Iterator<T> {
T next();
}
private static class Container<T> {
private T value;
public Container(T value) {
setValue(value);
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
private static Iterator<Integer> evenGenerator() {
final Container<Integer> i = new Container<>(0);
return new Iterator<Integer>() {
@Override
public Integer next() {
int tmp = i.getValue();
i.setValue(i.getValue() + 2);
return tmp;
}
};
}
public static void main(String[] args) {
Iterator<Integer> it = evenGenerator();
System.out.println(it.next()); // 0
System.out.println(it.next()); // 2
System.out.println(it.next()); // 4
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment