The motivation for introducing lambda expressions into Java is related to a pattern called
Using this method is simple enough. However, what if you need to also find invoices smaller than a certain amount? Or worse, what if you need to find invoices from a given customer
With this useful code, you can cope with any requirement changes involving any property of an Invoice object. You just need to create different InvoicePredicate objects and pass them to the findInvoices method. In other words, you have parameterized the behavior of findInvoices. Unfortunately, using this new method introduces additional verbosity, as shown here:
List
In other words, you have more flexibility but less readability. Ideally, you want both flexibility and conciseness, and that’s where lambda expressions come in. Using this feature, you can refactor the preceding code as follows:
List
Lambda Expressions Defined
Now that you know why you need need lambda expressions, it’s time to learn more precisely what they are. In the simplest terms, a lambda expression is an anonymous function that can be passed around. Let’s take a look at this definition in greater detail: Anonymous
A lambda expression is anonymous because it does not have an explicit name as a method normally would. It’s sort of like an anonymous class in that it does not have a declared name. Function
A lambda is like a method in that it has a list of parameters, a body, a return type, and a possible list of exceptions that can be thrown. However, unlike a method, it’s not declared as part of a particular class. Passed around
A lambda expression can be passed as an argument to a method, stored in a variable, and also returned as a result.
Lambda Expression Syntax
Before you can write your own lambda expressions, you need to know the syntax. You have seen a couple of lambda expressions in this guide already: Runnable r = () -> System.out.println("Hi"); FileFilter isXml = (File f) -> f.getName().endsWith(".xml");
These two lambda expressions have three parts:
A list of parameters, e.g. (File f)
An arrow composed of the two characters - and >
A body, e.g. f.getName().endsWith(".xml")
There are two forms of lambda expressions. You use the first form when the body of the lambda expression is a single expression: (parameters) -> expression