Mastering method references
Now, let’s move on to another important topic concerning lambda expressions, and that is method references. As concise as lambdas are, in certain situations, they can be even more concise! This is where method references apply. If all your lambda does is call one method, then this is an opportunity for a method reference. In addition, if a lambda parameter is simply passed to a method, then the redundancy of specifying the variable twice can also be removed.
Let’s look at an example:
List<String> names = Arrays.asList("Maaike", "Sean");names.forEach(name -> System.out.println(name); // lambda names.forEach(System.out::println); // method reference
In this code, we declare a list of strings by invoking the Arrays.asList()
method. The first forEach(Consumer)
shows how to output the list using a lambda expression. Recall that the functional method of Consumer
is void
accept(T t)
.
The second forEach(Consumer...