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>() {
    public void accept(String s) {
        String oneItem = s;

Because the Consumer interface is a functional interface (, the above code can be simplified with Lambda Expressions (

stringList.forEach((s) -> {
        String oneItem = s;

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:


No comments:

Get This <