2 Minutes Guide to Using Lambda Expressions in Java

By angsuman, Gaea News Network
Tuesday, July 21, 2015

Are you using Lambda expressions in Java? If not, you should start looking at them now for they are very powerful and reduce code clutter. The syntax is similar to Groovy and easy to learn. It allows you to embed an expression or method as an argument to another method, without requiring you to cumbersome inner classes. Here is an example:

Account a -> a.getSalary() < MIN_MANAGER_SALARY?? && a.getRank() >= Rank.MANAGER && a.getAge() > 30

This can be used as a argument in a method which expects Account object. Need I explain more?

Note: You can omit the data type.

Instead of defining functional interfaces to be used with lambda expressions, you can use generic interfaces defined in java.util.function as a convenience and for reducing code clutter.

Like local and anonymous classes, lambda expressions can capture variables; they have the same access to local variables of the enclosing scope. However, unlike local and anonymous classes, lambda expressions do not have any shadowing issues (see Shadowing for more information). Lambda expressions are lexically scoped. This means that they do not inherit any names from a supertype or introduce a new level of scoping. Declarations in a lambda expression are interpreted just as they are in the enclosing environment.

Like Groovy, you too can use Lambda expressions for aggregate operations:
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25)
.map(p -> p.getEmailAddress())
.forEach(email -> System.out.println(email));

It can heavily reduce GUI clutter which frequently uses functional interfaces, interfaces which contain a single method.

Hope that piques your interest and you delve into incorporating lambda expressions in your day to day work.

Filed under: Features, How To, Java Software
will not be displayed