Section 1
– Need changes to Java to simplify parallel coding.
– Lambda expressions simplify how to pass behavior as a parameter.
-Show the differences through Java basic code, inner classes and lambdas.
Non-functional (imperative) programming style versus functional.
Problem: external iteration.
After: more functional with inner classes;
And then: lambda approach, more concise, less code (error-prone), client logic is stateless, thread-safe.
The lambda expression provides the implementation of the abstract method. The type is the abstract method.
@FunctionalInterface -> Functional Interface = an interface with one abstract method; default doesn’t count. The equals also doesn’t count in therms of abstract method.
Variable assignment: Callable c = () -> process();
Method parameter: mew Thread(() -> process()).start();
Lambda expressions can be used anywhere the type is a functional interface.
– A functional interface has only one abstract method.
The lambda expression provides the implementation of the single abstract method of the functional interface.
java.util.function Package
Consumer<T>
Operation that takes a single value and return no result: String s -> System.out.println(s) .
Example: String s -> System.out.println(s);
BiConsumer<T,U>
Takes two values and returns no result.
Example: (k,v) -> System.out.println(“key: ” + k + “, value: ” + v);
Supplier
The opposite of a Consumer. Doesn’t take any parameter and returns a value.
Example: ( ) -> createLogMessage();
Function<T,R>
Takes one argument, do something and returns a result.
Example: Student s -> s.getName();
BiFunction<T,U,R>
Takes two arguments and returns a result.
Example: (String name, Student s) -> new Teacher(name, student);
UnaryOperator<T>
Kind function: single argument and result of the same type.
Example: String s -> s.toLowerCase();
BinaryOperartor<T>
Specialised form of BiFunction: two arguments and a result, all of the same type.
Example: (String x, String y) -> { if (x.length() > y.length()) return x; return y; }
Predicate
A boolean valued function of one argument:
Example: Student s -> s.graduationYear() == 2011
BiPredicate
Takes two arguments
Example: (Student s, int minGrade) -> s.grade <= minGrade
Method and constructor references
FileFilter x = (File f) -> f.canRead();
FileFilter x = File::canRead;
External variables
Final or effective final.
Link to the on line free Oracle course.