Java 8: Lambda expression example

29 03 2014

Lambda expression are a short-form replacement for anonymous classes. They help in cases where you have to declare an interface with a single abstract method (such an interface is called functional interface) and its implementation.


In short words
The function is now an Object since Java 8. It is now the first-class citizen, like primitives and other Objects. What does it mean? Now you can pass a function as an another method’s parameter. This is inspired by functional languages like Scala or JavaScript.

Before Java 8, to emulate method passing as a parameter, you had to use a dedicated object. Now, you can pass the method without packing it into object, using the notion of anonymous class definition.

Note: To compile Java 8 code, you need JDK 8 installed, and JRE, like Eclipse (Kepler with this plugin or Luna that in theory does not require any additional plugins. In reality. I also had to install the plugin  in Luna to make it compile with Java 8).

The syntax
Syntax is not obvious or self explanatory in my opinion, however I am sure I will get used to it. Basically to define the behaviour you use:

(formal parameter list comma separated) -> { expression or statements }

where parameters are related to your interface method declaration and the expression is just anonymous method body, where these parameters are processed.

The source code is here!
Feel free to download my sample eclipse Lambda demo project from here.

Let’s assume that we have a list of persons and print method that prints its items that satisfy condition. The condition is: Print only those, whose phone number begins with “+48”. We iterate over each item in list and call print method, that takes two parameters:
– the list item
– the function testing for defined condition

void printPerson(PersonInfo personInfo, PrintCondition condition)

Define functional interface
The PrintCondition is a functional interface with one method declaration:

public interface PrintCondition {
	public boolean isSatisfied(PersonInfo personInfo);

Method’s parameter list consists of one object: PersonInfo, and returns boolean indicating whether the condition is satisfied. We’re still in good old Java way of doing it.

The print method
Print method takes PersonInfo object and PrintCondition. If condition is satisfied, it prints the PersonInfo, otherwise does nothing:

private static void printPerson(PersonInfo personInfo, PrintCondition condition){

Here comes the Lambda!
I have a method that iterates over all list items and prints each, depending on condition. In my foreach loop I call the printPerson method with Lambda inside:

for (PersonInfo personInfo : persons) {
			//Here goes the lambda expression param:
			(PersonInfo person) -> {
				return person.getPhoneNumber().startsWith("+48");
			//that's it!

Basically speaking, this is the implementation of the PrintCondition’s interface method that is passed to printPerson body. I pass the PersonInfo param and get returned the boolean.

How would it look like without Lambda?
The same loop before Java 8 would be defined with an anonymous inner class implementing the PrintCondition interface, as follows:

for (PersonInfo personInfo : persons) {
		//Here we go without lambda!
		new PrintCondition() {
			public boolean isSatisfied(PersonInfo person) {
				return person.getPhoneNumber().startsWith("+48");

Reduce Lambda expression verbosity even more
There are some things to be reduced in my Lambda expression:
– you don’t need the curly braces around Lambda expression, if you have just one line of code
– you don’t need the return keyword. The statement’s return value will be returned automatically, if you have just one line of code
– you don’t need the semicolon at its end, if you have just one line of code
– you don’t have to pass parameter name, just its type

After applying clues above, the expression is now like that:

//Here goes even shorter lambda expression:
(PersonInfo) -> 

The shortest Lambda you can write
If you want your test condition to always evaluate to true (return true), the lambda expression would look like this:

(PersonInfo) -> true

But then why would you need the PersonInfo in this statement? If you refactor your interface method not to take any arguments like this:

public boolean isSatisfied();

The lambda would not need the PersonInfo param. Guess how it would look like? Well… exactly like that:

() -> true

Using built-in Java functional interfaces: Predicate
Here I used my own functional interface to provide test method. Such test is so widely used that such interface is a part of Java language under java.util.function.Predicate. It can get an object to test via generic argument and call your test method.

With the Predicate you don’t need the PrintCondition Interface at all. The lambda expression remains unchanged, the only change is in a print method declaration and body to get the Predicate param instead of PrintCondition, and then to call test() instead of PrintCondition’s isSatisfied():

private static void printPerson(PersonInfo personInfo, Predicate<PersonInfo> predicate){

The source code is here!
Feel free to download my sample eclipse Lambda demo project from here.

Other resources

Here are the other resources that can help you understand Lambdas:




Did I help you?
I manage this blog and share my knowledge for free, sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!



One response

28 06 2015
Java 8 Streams demo | Looks OK!

[…] on a result the item passes the filter or not. More about Lambda expressions you can read in post Lambda Expression example. The result […]

Give Your feedback:

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: