Computer Science 312 Lambdas in Java 1
Syntax of Java Lambdas (<parameters>) -> <expression> (<parameters>) -> {<statements> ;} (Apple a) -> a.getWeight() > 150 (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight()) (int x) -> x + 1
Context of Use Can be bound to a variable: Can be passed as an argument to a method or returned as a method’s value: Must conform to a functional interface in either case Predicate<Apple> isGreen = (Apple a) -> "green".equals(a.getColor()); List<Apple> greenApples = filter(inventory, (Apple a) -> "green".equals(a.getColor()));
Functional Interfaces A functional interface specifies exactly one method The signature of the method is similar to the signature of the lambda expression, which omits the name (called a function descriptor) public interface Predicate<T>{ boolean test(T t); } Predicate<Apple> isGreen = (Apple a) -> "green".equals(a.getColor()); List<Apple> greenApples = filter(inventory, isGreen);
Functional Interface for filter public interface Predicate<T>{ boolean test(T t); } public static <T> List<T> filter(List<T> list, Predicate<T> p) { List<T> results = new ArrayList<>(); for(T s: list){ if(p.test(s)){ results.add(s); return results; Predicate<String> nonEmptyStringPredicate = (String s) -> !s.isEmpty(); List<String> nonEmpty = filter(listOfStrings, nonEmptyStringPredicate);
Functional Interface for map public interface Function<T, R>{ R apply(T t); } public static <T, R> List<R> map(List<T> list, Function<T, R> f) { List<R> results = new ArrayList<>(); for(T s: list){ results.add(f.apply(s)); return results; List<Integer> lyst = map(Arrays.asList("I", "love", "functions!"), (String s) -> s.length());
Functional Interface for forEach public interface Consumer<T>{ void accept(T t); } public static <T> void forEach(List<T> list, Consumer<T> c) { for(T s: list){ c.accept(s); return results; forEach(Arrays.asList(1,2,3,4,5), (Integer i) -> System.out.println(i));
Specializations for Primitive Types @FunctionalInterface public interface IntPredicate{ boolean test(int i); } IntPredicate evenNumbers = (int i) -> i % 2 == 0; evenNumbers.test(1000); // Returns true
Bifunction Interface Where would this interface be used? @FunctionalInterface public interface BiFunction<T, U, V>{ V apply(T o1, U o2); } Where would this interface be used?
Introduction to Streams Chapter 4 For next time Introduction to Streams Chapter 4