Lambda expressions in Java 8 part 2: extended syntax and the function package
November 2, 2014 Leave a comment
Introduction
In the previous post in this short series we introduced the syntax of lambda expressions in Java 8. In this post we’ll look at a couple more facets of lambda expressions in Java: the ‘::’ operator and the new java.util.function package.
Syntactic sugar with ‘::’
There’s a new operator in Java 8: ‘::’, i.e. a double-colon. It’s used as a shortcut to write lambda expressions. Recall our Comparator implementation from the previous post:
Comparator<Employee> employeeAgeComparator = (employeeOne, employeeTwo) -> Integer.compare(employeeOne.getAge(), employeeTwo.getAge());
That was an Employee comparison where the input parameters were of type Employee but we compared their ages which are of type Integer. Say that we first collect the age values into a separate integer list. We can then write a pure integer comparator in a very similar way:
Comparator<Integer> intComparator = (int1, int2) -> Integer.compare(int1, int2);
This can be rewritten as follows:
Comparator<Integer> intComparatorShort = Integer::compare;
This way of writing the lambda expression is called a method reference. We first write the object on which we want to invoke a method, i.e. “Integer”, followed by a double-colon, and finally we have the name of the method. The compiler will infer from the Comparator type that we want to compare two integers so we don’t need to write compare(int1, int2). We’ll see other examples of this later on but the difference between this syntax and the one we saw in the previous post is purely syntactic. There’s no performance gain or loss with either of them.
java.util.function
Java.util.function is a new package that provides a range of functional interfaces. If you work in an IDE which provides intellisense – such as NetBeans – then you can type “import java.util.function.” above a class declaration to see the list of interfaces within this package. You’ll see names such as…
BiConsumer<T, U> Consumer<T> LongSupplier
At first these interfaces probably look quite strange. They are out-of-the box functional interfaces that represent some frequently used methods so that they can be written as lambda expressions. Examples:
- BiConsumer of T and U: represents a void method that accepts two arguments of types T and U
- Consumer of T: same as BiConsumer but it accepts a single parameter only
- IntSupplier: a method that returns an integer and accepts no arguments
- BiPredicate of T and U: a function that returns a boolean and accepts two arguments
- Function of T and R: a function that accepts an argument of type T and returns and object of type R
The input and output parameter types can be the same or different.
There are also specialised interfaces such as the UnaryOperator of T which extends Function of T and T. This means that UnaryOperator is a Function which returns an object of type T and returns an object of type T, i.e. both the input and output parameters are of the same type.
A simple example is System.out.println(String s). This is a void method that accepts a single argument of String, i.e. this fits the functional interface type of Consumer of String:
Consumer<String> systemPrint = s -> System.out.println(s);
We know from the above section that we can shorten this code to the following:
Consumer<String> systemPrint = System.out::println;
The Comparator of integers we saw above accepts two integers and returns another integer. This sounds like a BiFunction of int, int, int, i.e. a function that accepts 2 integers and returns another integer:
BiFunction<Integer, Integer, Integer> intComparatorFunctional = (t, t1) -> Integer.compare(t, t1);
…and as all types are the same we can use the shorthand notation:
BiFunction<Integer, Integer, Integer> intComparatorFunctional = Integer::compare;
We can further simplify this as there’s a specialised functional interface for the case of two integer inputs and one integer return value: IntBinaryOperator. The shortened version of the integer comparator looks like this:
IntBinaryOperator intComparatorAsBinaryOperator = Integer::compare;
So if you see that all parameters are of the same type then it’s worth checking what’s available in the java.util.function package because there might be a specialised interface. Choose the one that you think is most straightforward.
You can use these interfaces to pass around lambda expressions as input parameters. E.g. there’s a new method available for Collections, or objects that implement the Iterable interface to be exact: forEach, which accepts a Consumer of T. In other words you can iterate through the items in a collection and pass in a Consumer, i.e. a void method which accepts a single parameter to perform some action on each item in a collection in a single statement:
stringList.forEach(s -> System.out.println(s));
…or…:
stringList.forEach(System.out::println);
Other examples:
Add the items of a list to Employee objects to another list – we saw the Employee object in the previous post:
List<Employee> employees = new ArrayList<>(); List<Employee> employeesCopy = new ArrayList<>(); employees.add(new Employee(UUID.randomUUID(), "Elvis", 50)); employees.add(new Employee(UUID.randomUUID(), "Marylin", 18)); employees.add(new Employee(UUID.randomUUID(), "Freddie", 25)); employees.add(new Employee(UUID.randomUUID(), "Mario", 43)); employees.add(new Employee(UUID.randomUUID(), "John", 35)); employees.add(new Employee(UUID.randomUUID(), "Julia", 55)); employees.add(new Employee(UUID.randomUUID(), "Lotta", 52)); employees.add(new Employee(UUID.randomUUID(), "Eva", 42)); employees.add(new Employee(UUID.randomUUID(), "Anna", 20)); Consumer<Employee> copyEmployees = employeesCopy::add; employees.forEach(copyEmployees);
employeesCopy will have the same objects as the employees list.
You can even chain Consumers with the “andThen” interface method:
Consumer<Employee> copyEmployees = employeesCopy::add; Consumer<Employee> printEmployeeName = (Employee e) -> System.out.println(e.getName()); employees.forEach(copyEmployees.andThen(printEmployeeName));
View all posts related to Java here.