Using Lexical Scoping and Closures

There’s a misconception among some developers that using lambda expressions may introduce duplication and lower code quality. Contrary to that belief, even when the code gets more complicated we still don’t need to compromise code quality to enjoy the conciseness that lambda expressions give, as we’ll see in this section.

We managed to reuse the lambda expression in the previous example; however, duplication will sneak in quickly when we bring in another letter to match. Let’s explore the problem further and then solve it using lexical scoping and closures.

Duplication in Lambda Expressions

Let’s pick the names that start with N or B from the friends collection of names. Continuing with the previous example, ...

Get Functional Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.