Skip to content

Instantly share code, notes, and snippets.

@delexi
Created June 7, 2013 20:45
Show Gist options
  • Save delexi/5732300 to your computer and use it in GitHub Desktop.
Save delexi/5732300 to your computer and use it in GitHub Desktop.
A simple attempt at Higher Order functions in Java.
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
class HigherOrder {
public static void main(String[] args) {
Iterable<Integer> it = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Iterable<Integer> evens = keep(it, new Function1<Boolean, Integer>() {
public Boolean map(Integer x) {
return x % 2 == 0;
}
});
Iterator<Integer> iter = evens.iterator();
for (Integer i : evens) { System.out.println(i); }
}
interface Function1<R,T> {
R map(T t);
}
public static <E> Iterable<E> keep(final Iterable<? extends E> itr, final Function1<Boolean,E> f) {
return new Iterable<E>() {
public Iterator<E> iterator() {
return new Iterator<E>() {
Iterator<? extends E> oldIter = itr.iterator();
E cache = null;
public boolean hasNext() {
while (oldIter.hasNext() && cache == null) {
E elem = oldIter.next();
if (f.map(elem)) {
cache = elem;
return true;
}
}
return cache != null;
}
public E next() {
if (cache != null || hasNext()) {
E tmp = cache;
cache = null;
return tmp;
}
throw new NoSuchElementException();
}
public void remove() { oldIter.remove(); }
};
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment