Skip to content

Instantly share code, notes, and snippets.

@nicerobot
Last active December 11, 2015 09:48
Show Gist options
  • Save nicerobot/4582185 to your computer and use it in GitHub Desktop.
Save nicerobot/4582185 to your computer and use it in GitHub Desktop.
An example of writing `take` in Java.
package org.nicerobot;
import java.util.Iterator;
interface Applyable<T> {
public T apply (Integer n);
}
public class Take {
public static void main (final String[] args) {
new Take().test();
}
public void test () {
final Applyable<String> square = new Applyable<String>() {
@Override
public String apply (final Integer value) {
return String.format("%d\t%d", value, value * value);
}
};
for (final String s : this.take(25, square)) {
System.out.println(s);
}
}
private <T> Iterable<T> take (final Integer i, final Applyable<T> f) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator () {
return new Iterator<T>() {
private Integer n = 0;
@Override
public boolean hasNext () {
return this.n + 1 < i.intValue();
}
@Override
public T next () {
return f.apply(++this.n);
}
@Override
public void remove () {}
};
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment