Learnitweb

Java 8 Lambdas – an introduction

To understand lambdas introduced in Java 8, let us first see how things were implemented before Java 8 and then we’ll see how lambda expressions make our life easy. We believe everyone has heard about Swing in Java. Even if you haven’t heard, you must be having some idea about a button and adding some functionality on click of a button. Have a look at the below code:

button.addActionListener(new ActionListener() {
	public void actionPerformed(ActionEvent event) {
		System.out.println("Hi!!! Button clicked");
	}
});

The syntax may be different but it is done is a similar fashion in JavaScript and many other languages. Here, we’ll talk in context of Java.

In this example, we’re creating a new object that provides an implementation of the ActionListener. This interface has a single method, actionPerformed, which is called by the button instance when a user actually clicks the button. In this example, anonymous inner class provides the implementation of this method. The functionality of this method is just to print message “Hi!!! Button clicked”. In this example, the object represents as action and we can say that we are passing code as data. 

The problem here is even if we want to pass the behavior, we have to write some boilerplate code and object needs to be created to contain behavior.

The same code can be written in Java 8 as shown below:

button.addActionListener(event -> System.out.println("Hi!!! Button clicked"));

If you don’t understand the syntax here, please continue reading our tutorials on lambdas.

A Java lambda expression can be passed around as if it was an object and executed on demand. Here, we are passing the behavior itself but not an object. The function passed here doesn’t have a name.

Advantages of using Lambda expression

  • Lambda expression provides functional programming capability to Java.
  • Using lambda expression, functions can be treated as values and can be passed around like values.
  • Lambda expression help in writing concise and more readable code.
  • Lambda expression can be used instead of anonymous inner class for some cases. This helps in reducing complexity and boilerplate code associated with anonymous inner class.
  • Lambda expression provides support for parallel processing.