Teach you to understand Java Lambda expressions and learn how to use them in one minute

  • 2021-09-11 20:31:48
  • OfStack

Catalog 1. Foreword 2. Lambda expression syntax 3. Environment requirements for running Lambda expression samples. 4. Example 1: Combining Runnable with Lambda Expression5. Example 2: Custom Function Interface Using Lambda Expression6. Example 3: Combining Comparator (Comparator) with Lambda Expression7. Example 4: Iterating a Collection with Lambda Expression8. References

1. Preface

Lambda The expression is java 8 One of the important functions contained in. Lambda Expressions are used to write concise code for an interface consisting of one method, that is, a function interface ( functional interface ). Lambda Expressions are also used to traverse collections in a simple way. For an interface with a single 1 method, whether we use anonymous classes or inner classes, it can also be implemented in the java 8 Use in Lambda Expression to implement very concise code. Lambda The expression defines the function interface method and returns an instance of the interface.

2. Lambda expression syntax

Lambda expression syntax is very easy to read and understand.

Lambda expression syntax looks like


(Argument  part)  -> Body part 

Here are some examples

Example 1: Print a message if the method does not require parameters.


() ->    System.out.println("Your message");

Example 2: If the method accepts two parameters and executes some business logic and returns a value.


(int a, int b) ->  a+b;

Method returns the value of a+b.

Example 3: If the method accepts 1 parameter and executes 1 business logic.


(String s) ->  s + "Hello World"; 

A string is returned after connection.

3. Environment requirements for running the Lambda expression sample.

JDK 8+

4. Example 1: Combining Runnable with Lambda expressions

In the following example, we are running 1 Runnable Thread.

In lambda Expression, in order to implement a runnable thread, we need to define an implementation Runnable Interface to get a runnable object.

Now look at how to use the lambda Expression to implement the same object

RunnableDemo.java


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class RunnableDemo {
	public static void main(String[] args) {
	final ExecutorService exService = Executors.newSingleThreadExecutor();
        Runnable r = () -> System.out.println("Lambda Expression Test with Runnable");
        exService.execute(r);
     }
}

The output will be

Lambda Expression Test with Runnable

5. Example 2: Example of a custom function interface using an Lambda expression

In this example, we will create our own functional interface and learn how to connect it with the lambda The expression 1 is used.

Find the function interface.

Calculator.java


package com.concretepage.lambda;
public interface Calculator {
    public int add(int n1, int n2);    
}

Find out how the main class uses the function interface lambda Expression.

CalculatorDemo.java


public class CalculatorDemo {
    public static void main(String[] args) {
        Calculator cal =(int a, int b) -> a+b;
        int res = cal.add(5, 6);
        System.out.println(res);
    }
}

The output will be 11 .

6. Example 3: Combining a comparator (Comparator) with an Lambda expression

View now Comparator How to use the interface lambda Expression sorts the collection containing user-defined objects.

ComparatorDemo.java


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparatorDemo {
    public static void main(String[] args) {
        List<Student> list = new ArrayList();
        list.add(new Student("Ram",20));
        list.add(new Student("Shyam",22));
        list.add(new Student("Kabir",18));
        System.out.println("...befor sorting...");
        for(Student s : list){
            System.out.println(s.getName());
        }    
        //define comparator
        Comparator<Student> comp= (Student s1, Student s2) -> s1.getName().compareTo(s2.getName());
        Collections.sort(list, comp);
        System.out.println("...after sorting...");
        for(Student s : list){
            System.out.println(s.getName());
        }
    }
}

Student.java


public class Student {
    private String name;
    private int age;
    public Student(String name,int age){
        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;
    }
 } 

Output

...befor sorting...
Ram
Shyam
Kabir
...after sorting...
Kabir
Ram
Shyam

7. Example 4: Iterating through a collection with an Lambda expression using a function interface

In java 8 Introduced in java.util.function Bag. In java.util.function.Function API With the help of, we will use lambda Expression iteration collection.

In Function Interface has apply() Method, which will be called in a user-defined function.

Assuming we must create a method for custom printing, we will define the method as follows.


public  String customShow(Function<Student,String> fun){
    return fun.apply(this);
}

In Student Class to run the following example.

FunctionDemo.java


() ->    System.out.println("Your message");
0

Output

Ram: 20
Shyam: 22
Kabir: 18

8. References

"1" Lambda Expressions Java 8 Example


Related articles: