Java Lambda Expression Tutorial with Examples

In this tutorial, we will see some 11 useful Lambda Expressions examples in Java.

Source Code on GitHub

The source code examples created in this tutorial are hosted on my GitHub repository at Java 8 Lambda Source Code

Java 8 Lambda Expressions Syntax

Java Lambda Expression Syntax
(argument-list) -> {body}  
Java lambda expression consists 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 the lambda expression.

Useful Java Lambda Expressions Examples

1. Java Simple Lambda Expression Example

Here, we are implementing a Drawable functional interface method using the lambda expression:
interface Drawable{  
    public void draw();  
}  
public class LambdaExpressionExample {  
    public static void main(String[] args) {  
        int width=10;         
        //with lambda 
        Drawable withLambda=()->{  
            System.out.println("Drawing "+width);  
        };  
        withLambda.draw();  
    }  
} 
Output :
Drawing 10

2. Java Lambda Expression Example: No Parameter

Please refer to the comments in the code, which indicates that code with Lambda expression and without Lambda expression.
interface Sayable {
    public String say();
}
public class JLEExampleNoParameter {
    public static void main(String[] args) {
        // without lambda expression
        Sayable sayable = new Sayable() {
            @Override
            public String say() {
                return "Return something ..";
            }
        };
        sayable.say();

        // with lambda expression
        Sayable withLambda = () -> {
            return "Return something ..";
        };
        withLambda.say();
    }
}

3. Java Lambda Expression Example: Single Parameter

Please refer to the comments in the code, which indicates that code with Lambda expression and without Lambda expression.
interface Printable {
    void print(String msg);
}

public class JLEExampleSingleParameter {

    public static void main(String[] args) {
     // without lambda expression
         Printable printable = new Printable() {
            @Override
            public void print(String msg) {
               System.out.println(msg);
            }
         };
         printable.print(" Print message to console....");
  
         // with lambda expression
         Printable withLambda = (msg) -> System.out.println(msg);
         withLambda.print(" Print message to console....");
     }
}
Output :
 Print message to console....
 Print message to console....

4. Java Lambda Expression Example: Multiple Parameters

Please refer to the comments in the code, which indicates that code with Lambda expression and without Lambda expression.
interface Addable{  
    int add(int a,int b);  
}  
public class JLEExampleMultipleParameters {

 public static void main(String[] args) {
  
     // without lambda expression
  Addable addable = new Addable() {
   @Override
   public int add(int a, int b) {
    return a + b;
   }
  };
  addable.add(10, 20);
  
  // with lambda expression
   // Multiple parameters in lambda expression  
        Addable withLambda = (a,b)->(a+b);  
        System.out.println(withLambda.add(10,20));  
          
        // Multiple parameters with data type in lambda expression  
        Addable withLambdaD = (int a,int b) -> (a+b);  
        System.out.println(withLambdaD.add(100,200));  
 }
 
}

5. Java Lambda Expression Example: Multiple Statements

Let's see how to write multiple statements in Lambda expressions:
interface IAvarage{  
    double avg(int[] array);  
}  
public class JLEExampleMultipleStatements {

    public static void main(String[] args) {
  
        // without lambda expression, IAvarage implementation using anonymous class  
         IAvarage avarage = new IAvarage() {
            @Override
            public double avg(int[] array) {
                double sum = 0;
                int arraySize = array.length;
    
                System.out.println("arraySize : " + arraySize);
                for (int i = 0; i < array.length; i++) {
                    sum = sum + array[i]; 
                } 
                System.out.println("sum : " + sum);
    
                return (sum/ arraySize);
           }
        };
        int[] array = {1,4,6,8,9};
        System.out.println(avarage.avg(array));
  
        // with a lambda expression
        // You can pass multiple statements in lambda expression 
  
        IAvarage withLambda = (withLambdaArray) -> {
            double sum = 0;
            int arraySize = withLambdaArray.length;
   
            System.out.println("arraySize : " + arraySize);
            for (int i = 0; i < withLambdaArray.length; i++) {
                sum = sum + withLambdaArray[i]; 
            }
            System.out.println("sum : " + sum);
   
            return (sum/ arraySize);
       };
  
        int[] withLambdaArray = {1,4,6,8,9};
        System.out.println(withLambda.avg(withLambdaArray)); 
    }
}

6. Java Lambda Expression Example: Creating Thread

Let's write the example to use a lambda expression to implement Runnable interface:
public class JLEExampleRunnable {

    public static void main(String[] args) {
  
    //without lambda, Runnable implementation using anonymous class  
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            System.out.println(" Runnable example without lambda exp.");
        }
    };
    Thread thread = new Thread(runnable);
    thread.start();
  
     //with lambda 
    Runnable withLambda = () -> System.out.println(" Runnable example with lambda exp.");
    Thread thread1 = new Thread(withLambda);
    thread1.start();
  }
}
Output :
 Runnable example without lambda exp.
 Runnable example with lambda exp.

7. Java Lambda Expression Example: Comparator

Let's write an example to demonstrate how to use a lambda expression to implement Comparator interface:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class JLEComparatorExample {

    public static void main(String[] args) {

        List<Person> listOfPerson = new ArrayList<Person>();
        listOfPerson.add(new Person("abc", 27));
        listOfPerson.add(new Person("mno", 26));
        listOfPerson.add(new Person("pqr", 28));
        listOfPerson.add(new Person("xyz", 27));

        // Without lambda expression.
        // Sort list by age
        Comparator<Person> comparator = new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                return o1.getAge() - o2.getAge();
            }
        };

        Collections.sort(listOfPerson, comparator);

        System.out.println(" sort persons by age in ascending order");
        for (Person person : listOfPerson) {
            System.out.println(" Person name : " + person.getName());
        }

        // With lambda expression.
        // Sort list by age

        Collections.sort(listOfPerson, (Person o1, Person o2) -> {
            return o1.getAge() - o2.getAge();
        });
        // Use forEach method added in java 8
        System.out.println(" sort persons by age in ascending order");
        listOfPerson.forEach(
           (person) -> System.out.println(" Person name : " + person.getName()));
        }
  }

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
       super();
       this.name = name;
       this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

8. Java Lambda Expression Example: Event Listener

import javax.swing.JButton;  
import javax.swing.JFrame;  
import javax.swing.JTextField;  
public class LambdaEventListenerExample {  
    public static void main(String[] args) {  
        JTextField tf=new JTextField();  
        tf.setBounds(50, 50,150,20);  
        JButton b=new JButton("click");  
        b.setBounds(80,100,70,30);  
        // lambda expression implementing here.  
        b.addActionListener(e-> {tf.setText("hello swing");});  
        JFrame f=new JFrame();  
        f.add(tf);f.add(b);  
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        f.setLayout(null);  
        f.setSize(300, 200);  
        f.setVisible(true);  
    }  
} 

9. Iterate ArrayList with forEach() method + Lambda Expression Example

package net.javaguides.collections;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * 
 * Java program to demonstrate different ways to Iterate over an ArrayList in Java
 * @author Ramesh Fadatare
 *
 */
public class DifferentWaysListIterateProgram {

    public static void main(String...args) {

        List < String > courses = Arrays.asList("C", "C++", "Core Java", "J2EE", "Spring", "Hibernate", "Python");

   
        // JDK 8 streaming example lambda expression
        courses.stream().forEach(course -> printCourse(course));

        // JDK 8 streaming example method reference
        courses.stream().forEach(DifferentWaysListIterateProgram::printCourse);

        // JDK 8 for each with lambda
        courses.forEach(course -> printCourse(course));

        // JDK 8 for each
        courses.forEach(DifferentWaysListIterateProgram::printCourse);
    }

    // common method to print course
    private static void printCourse(String course) {
        System.out.println("course name :: " + course);
    }
}

10. Iterate HashSet with forEach() method + Lambda Expression Example

package net.javaguides.collections;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Java program to demonstrate different ways to iterate over a Set in Java
 * 
 * @author Ramesh Fadatare
 *
 */
public class DifferentWaysSetIterateProgram {

    public static void main(String...args) {

        Set < String > courses = new HashSet < String > ();
        courses.add("Java");
        courses.add("C");
        courses.add("C++");
        courses.add("Python");
        courses.add("Scala");

        // JDK 8 streaming example lambda expression
        courses.stream().forEach(course -> coursePrinter(course));

        // JDK 8 streaming example method reference
        courses.stream().forEach(DifferentWaysSetIterateProgram::coursePrinter);

        // JDK 8 for each with lambda
        courses.forEach(course -> coursePrinter(course));

        // JDK 8 for each
        courses.forEach(DifferentWaysSetIterateProgram::coursePrinter);
    }

    // common method to print course
    private static void coursePrinter(String course) {
        System.out.println("course name :: " + course);
    }
}

11. Iterate HashMap with forEach() method + Lambda Expression Example

package net.javaguides.collections;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * This program demonstrate different ways to iterate over a Map in Java
 * 
 * @author Ramesh Fadatare
 *
 */
public class DifferentWaysMapIterateProgram {

    public static void main(String...args) {

        Map < Integer, String > coursesMap = new HashMap < Integer, String > ();
        coursesMap.put(1, "C");
        coursesMap.put(2, "C++");
        coursesMap.put(3, "Java");
        coursesMap.put(4, "J2EE");
        coursesMap.put(5, "Python");
        coursesMap.put(6, "Scala");

   
        // JDK 8 for each with lambda
        coursesMap.forEach((k, v) -> coursePrinter(k, v));

        // JDK 8 for each method reference
        coursesMap.forEach(DifferentWaysMapIterateProgram::coursePrinter);

    }

    // common method to print map key value
    private static void coursePrinter(Integer number, String brand) {
        System.out.println("course no : " + number + " and course name : " + brand);
    }
}

References

Comments

  1. Excelent post, but there is an issue in the example on point 6. "Java Lambda Expression Example: Creating Thread"

    //with lambda
    Runnable withLambda = () -> System.out.println(" Runnable example with lambda exp.");
    Thread thread1 = new Thread(runnable);
    thread1.start();


    Replace witth:

    //with lambda
    Runnable withLambda = () -> System.out.println(" Runnable example with lambda exp.");
    Thread thread1 = new Thread(withLambda);
    thread1.start();

    ReplyDelete

Post a Comment