java lambda tutorial

Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a clear and concise way to represent one method interface using an expression. It is very useful in collection library. It helps to iterate, filter and extract data from collection.

The Lambda expression is used to provide the implementation of an interface which has functional interface. It saves a lot of code. In case of lambda expression, we don’t need to define the method again for providing the implementation. Here, we just write the implementation code.

Java lambda expression is treated as a function, so compiler does not create .class file.

What are lambda expressions?

Lambda expressions are an anonymous function, meaning that they have no name or identifier. They can be passed as a parameter to another function. They are paired with a functional interface and feature a parameter with an expression that references that parameter.

The syntax of a basic lambda expression is:

parameter -> expression

To use more than one parameter, wrap them in parentheses:

(parameter1, parameter2) -> expression

The expression is used as the code body for the abstract method (a named but empty method) within the paired functional interface.

Unlike most functions in Java, lambda expressions exist outside of any object’s scope. This means they are callable anywhere in the program and can be passed around. In the simplest terms, lambda expressions allow functions to behave like just another piece of data.

Expressions are limited. They have to immediately return a value, and they cannot contain variables, assignments or statements such as if or for. In order to do more complex operations, a code block can be used with curly braces. If the lambda expression needs to return a value, then the code block should have a return statement.

Why use Lambda Expression

  1. To provide the implementation of Functional interface.
  2. Less coding.

Java Lambda Expression Syntax

  1. (argument-list) -> {body}  

Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.

2) Arrow-token: It is used to link arguments-list and body of expression.

3) Body: It contains expressions and statements for lambda expression.

Using Lambda Expressions

Lambda expressions are usually passed as parameters to a function:

Example

Use a lamba expression in the ArrayList‘s forEach() method to print every item in the list:

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(9);
    numbers.add(8);
    numbers.add(1);
    numbers.forEach( (n) -> { System.out.println(n); } );
  }

Lambda expressions can be stored in variables if the variable’s type is an interface which has only one method. The lambda expression should have the same number of parameters and the same return type as that method. Java has many of these kinds of interfaces built in, such as the Consumer interface (found in the java.util package) used by lists.

Example

Use Java’s Consumer interface to store a lambda expression in a variable:

import java.util.ArrayList;
import java.util.function.Consumer;

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(9);
    numbers.add(8);
    numbers.add(1);
    Consumer<Integer> method = (n) -> { System.out.println(n); };
    numbers.forEach( method );
  }
}

To use a lambda expression in a method, the method should have a parameter with a single-method interface as its type. Calling the interface’s method will run the lambda expression:

Example

Create a method which takes a lambda expression as a parameter:

interface StringFunction {
  String run(String str);
}

public class Main {
  public static void main(String[] args) {
    StringFunction exclaim = (s) -> s + "!";
    StringFunction ask = (s) -> s + "?";
    printFormatted("Hello", exclaim);
    printFormatted("Hello", ask);
  }
  public static void printFormatted(String str, StringFunction format) {
    String result = format.run(str);
    System.out.println(result);
  }
}

Lambda expression vs method in Java

A method (or function) in Java has these main parts:
1. Name
2. Parameter list
3. Body
4. return type.

A lambda expression in Java has these main parts:
Lambda expression only has body and parameter list.
1. No name – function is anonymous so we don’t care about the name
2. Parameter list
3. Body – This is the main part of the function.
4. No return type – The java 8 compiler is able to infer the return type by checking the code. you need not to mention it explicitly.

Where to use the Lambdas in Java

To use lambda expression, you need to either create your own functional interface or use the pre defined functional interface provided by Java. An interface with only single abstract method is called functional interface(or Single Abstract method interface), for example: Runnable, callable, ActionListener etc.

To use function interface:
Pre Java 8: We create anonymous inner classes.
Post Java 8: You can use lambda expression instead of anonymous inner classes.

Java Lambda expression Example

Without using Lambda expression: Prior to java 8 we used the anonymous inner classe to implement the only abstract method of functional interface.

import java.awt.*;  
import java.awt.event.*;  
public class ButtonListenerOldWay {  
    public static void main(String[] args) {  
       Frame frame=new Frame("ActionListener Before Java8");  
    
       Button b=new Button("Click Here");  
       b.setBounds(50,100,80,50);  
  
       b.addActionListener(new ActionListener(){  
          public void actionPerformed(ActionEvent e){  
    	     System.out.println("Hello World!"); 
          }  
       });  
       frame.add(b);
    
       frame.setSize(200,200);  
       frame.setLayout(null);  
       frame.setVisible(true);   
    }  
}

By using Lambda expression: Instead of creating anonymous inner class, we can create a lambda expression like this:

import java.awt.*;  
public class ButtonListenerNewWay {  
   public static void main(String[] args) {  
      Frame frame=new Frame("ActionListener java8");  
     
      Button b=new Button("Click Here");  
      b.setBounds(50,100,80,50); 
  
      b.addActionListener(e -> System.out.println("Hello World!")); 
      frame.add(b);
  
      frame.setSize(200,200);  
      frame.setLayout(null);  
      frame.setVisible(true);   
   }  
}

Note:
1. As you can see that we used less code with lambda expression.
2. Backward compatibility: You can use the lambda expression with your old code. Lambdas are backward compatible so you can use them in existing API when you migrate your project to java 8.

Lets see few more examples of Lambda expressions.

Example 1: Java Lambda Expression with no parameter

@FunctionalInterface
interface MyFunctionalInterface {

	//A method with no parameter
    public String sayHello();
}
public class Example {

   public static void main(String args[]) {
        // lambda expression
    	MyFunctionalInterface msg = () -> {
    		return "Hello";
    	};
        System.out.println(msg.sayHello());
    }
}

Output:

Hello

Example 2: Java Lambda Expression with single parameter

@FunctionalInterface
interface MyFunctionalInterface {

	//A method with single parameter
    public int incrementByFive(int a);
}
public class Example {

   public static void main(String args[]) {
        // lambda expression with single parameter num
    	MyFunctionalInterface f = (num) -> num+5;
        System.out.println(f.incrementByFive(22));
    }
}

Output:

27

Example 3: Java Lambda Expression with Multiple Parameters

interface StringConcat {

    public String sconcat(String a, String b);
}
public class Example {

   public static void main(String args[]) {
        // lambda expression with multiple arguments
    	StringConcat s = (str1, str2) -> str1 + str2;
        System.out.println("Result: "+s.sconcat("Hello ", "World"));
    }
}

Output:

Result: Hello World

Example 4: Iterating collections using foreach loop

import java.util.*;  
public class Example{  
    public static void main(String[] args) {       
       List<String> list=new ArrayList<String>();  
       list.add("Rick");         
       list.add("Negan");       
       list.add("Daryl");         
       list.add("Glenn");         
       list.add("Carl");                
       list.forEach(          
           // lambda expression        
           (names)->System.out.println(names)         
       );     
    }  
}

learn core java programming – beginner to master For free

Leave a Comment