Monday, April 22, 2019

Java: example of Lambda Expressions and Method References


In this post, we showed an example of using anonymous class in the forEach method to loop over a list.

stringList.forEach(new Consumer<String>() {
    @Override
    public void accept(String s) {
        String oneItem = s;
        System.out.println(oneItem);
    }
});


Because the Consumer interface is a functional interface (https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html), the above code can be simplified with Lambda Expressions (https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html)


stringList.forEach((s) -> {
        String oneItem = s;
        System.out.println(oneItem);
});


or even:

stringList.forEach(s -> System.out.println(s));

And because the above Lambda Expresso does nothing but call only an existing method, we can use Method References to write the code this way:

stringList.forEach(System.out::println);


No comments:

 
Get This <