Skip to content

Instantly share code, notes, and snippets.

@gkossakowski
Created April 21, 2013 05:13
Show Gist options
  • Save gkossakowski/5428572 to your computer and use it in GitHub Desktop.
Save gkossakowski/5428572 to your computer and use it in GitHub Desktop.
Playing around with Java lambdas.
import java.util.*;
import java.util.function.Predicate;
import java.util.function.Consumer;
public class Collections8 {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
forEach(filter(names, e -> e.length() > 4), e -> { System.out.println(e); });
//names.filter().forEach(e -> { System.out.println(e); });
}
private static <T> List<T> filter(List<T> list, Predicate<T> p) {
List<T> buf = new ArrayList<T>();
for (T e : list) {
if (p.test(e))
buf.add(e);
}
return buf;
}
private static <T> void forEach(List<T> list, Consumer<T> f) {
for (T e : list) {
f.accept(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment