search
HomeJavajavaTutorialHow to use Lambda expressions in Java?
How to use Lambda expressions in Java?Apr 21, 2023 pm 08:31 PM
javalambda

Introduction to Lambda expressions

  • #The essence of Lambda expression is just a "syntax sugar", which is inferred by the compiler and helps you convert and wrap it into regular code , so you can use less code to achieve the same functionality.

  • Lambda expressions are an important new feature in Java SE 8.

Lambda and anonymous inner classes

Lamda expression refers to application in SAM (SingleAbstractMethod, an interface containing an abstract method) environment A simplified form of definition.

Advantages of Lambda over anonymous inner classes

Conciseness (see "Functional Interface" below for details)

Lamda over anonymous inner classes Disadvantages of the class

  • #The interface corresponding to Lamda can only have one method.

  • The interface corresponding to the anonymous inner class can have multiple methods

Requirements for the interface

1.Lambda stipulates that there can only be one method that needs to be implemented in the interface (ie, abstract method).

In an interface, the following ones can exist at the same time: one abstract method (there can only be one), multiple default methods, and multiple static methods.

// There is another new feature in jdk 8: default. The method modified by default will have a default implementation and is not a method that must be implemented, so it does not affect the use of Lambda expressions.

2.@FunctionalInterface: Used to modify functional interfaces.

@FunctionalInterface can be written or not. This annotation is mainly used for compile-level error checking: when the interface does not conform to the functional interface definition, the compiler will report an error.

Correct example, no error reported:

@FunctionalInterface
public interface HelloWorldService {
    void sayHello(String msg);
}

Incorrect example, error reported:

The interface contains two abstract methods, which violates the definition of functional interface, prompting that the interface Multiple non-overridden abstract methods were found.

How to use Lambda expressions in Java?

Note: Adding or not adding @FunctionalInterface has no effect on whether the interface is a functional interface. This annotation only reminds the compiler to check whether the interface only contains one abstract method.

Variables and scope

  • Lambda expressions can only reference outer local variables marked final. That is, local variables defined outside the scope cannot be modified inside the lambda, otherwise a compilation error will be reported

  • The local variables of the Lambda expression do not need to be declared final, but they must not be modified by subsequent code (i.e. Implicitly with final semantics)

  • Lambda expressions are not allowed to declare a parameter or local variable with the same name as a local variable.

Format

Important features of lambda expressions

  • Optional type declaration: No need to declare parameter types, the compiler Parameter values ​​can be identified uniformly.

  • Optional parameter parentheses: One parameter does not need to be defined with parentheses, but multiple parameters need to be defined with parentheses.

  • Optional braces: If the body contains a statement, braces are not required. Example: () -> Sysout.out.println("Test");

  • Optional return keyword: If the body has only one expression return value, the compiler will automatically Return value, curly braces need to be specified to indicate that the expression returns a value.

Simple example of Lambda expression

1. No parameters are required, the return value is 5

() -> 5

2. Receive one parameter (number type) and return 2 times its value

x -> 2 * x

3. Accept 2 parameters (number) and return them The difference

(x, y) -> x – y

4. Receive 2 int type integers and return their sum

(int x, int y) -> ; System.out.print(s)

Syntax format

Format:

(parameters) - > statement or (parameters) ->{ statements; }

Left side: the parameter list of the Lambda expressionRight side: the functions that need to be performed in the Lambda expression (Lambda body)

Syntax format 1: no parameters, no return value

##() -> Sysout.out.println("Test") ;

Syntax format 2: There is one parameter and no return value

(X)-> Sysout.out.println(x );

Grammar format three: If there is a parameter bracket, you don’t need to write it

##X-> Sysout.out.println(x) ;

Grammar format 4: There are more than two parameters, a return value, and there are multiple statements in the Lambda body. {}

needs to be used in the syntax body. <pre class='brush:php;toolbar:false;'> Comparator&lt;Integer&gt; comparator = (o1, o2) -&gt; { System.out.println(&quot;Test&quot;); return Integer.compare(o1, o2); };</pre>

Grammar format 5: Only one statement is used in the Lambda body, return and {} can be omitted

##Comparator comparator = (o1, o2)-> Integer.compare(o1, o2);

语法格式六:表达式的参数列表的数据类型可以省略不写,JVM编译器通过上下文推断出数据类型

(x ,y ) ->Integer.compare(x ,y)

实例

无参数无返回值

package org.example.a;
 
@FunctionalInterface
interface Interface {
    void run();
}
 
public class Demo{
    public static void main(String[] args) {
        Interface params = new Interface() {
            @Override
            public void run() {
                System.out.println("Anonymous Internal Class: ");
            }
        };
 
        Interface params1 = () -> System.out.println("Lambda: ");
 
        params.run();
        params1.run();
    }
}

执行结果

Anonymous Internal Class: 
Lambda: 

有参数无返回值

package org.example.a;
 
@FunctionalInterface
interface Interface {
    void run(String s);
}
 
public class Demo{
    public static void main(String[] args) {
        Interface params = new Interface() {
            @Override
            public void run(String s) {
                System.out.println("Anonymous Internal Class: " + s);
            }
        };
 
        Interface params1 = (s) -> System.out.println("Lambda: " + s);
 
        params.run("hello");
        params1.run("hi");
    }
}

执行结果

Anonymous Internal Class: hello
Lambda: hi 

有参数有返回值

package org.example.a;
 
@FunctionalInterface
interface Interface {
    String run(String s);
}
 
public class Demo{
    public static void main(String[] args) {
        Interface params = new Interface() {
            @Override
            public String run(String s) {
                System.out.println("Anonymous Internal Class: " + s);
                return "abc";
            }
        };
 
        Interface params1 = (s) -> {
            System.out.println("Lambda: " + s);
            return "def";
        };
 
        System.out.println(params.run("hello"));
        System.out.println(params1.run("hi"));
    }
}

执行结果

Anonymous Internal Class: hello
abc
Lambda: hi
def 

lambda作为参数

传递一个函数

package org.example.a;
 
interface IRun {
    String welcome(String string);
}
 
class Util {
    public static long executionTime1(IRun iRun, String string) {
        long startTime = System.currentTimeMillis();
        System.out.println(iRun.welcome(string));
        //本处刻意添加这一无意义延时,防止执行太快返回0
        try {
            Thread.sleep(10);
        } catch (Exception e) {
            System.out.println(e);
        }
        long endTime = System.currentTimeMillis();
        return endTime - startTime;
    }
 
    public long executionTime2(IRun iRun, String string) {
        long startTime = System.currentTimeMillis();
        System.out.println(iRun.welcome(string));
        //本处刻意添加这一无意义延时,防止执行太快返回0
        try {
            Thread.sleep(10);
        } catch (Exception e) {
            System.out.println(e);
        }
        long endTime = System.currentTimeMillis();
        return endTime - startTime;
    }
 
    public static String hello(String string){
        String tmp;
        tmp = "hello: " + string;
        return tmp;
    }
 
    public String hi(String string){
        String tmp;
        tmp = "hi: " + string;
        return tmp;
    }
}
 
public class Demo {
    public static void main(String[] args) {
        long time1 = Util.executionTime1(Util::hello, "Tony");
        long time2 = new Util().executionTime2(new Util()::hi, "Pepper");
        System.out.println("time1: " + time1 + "ms");
        System.out.println("time2: " + time2 + "ms");
    }
}

执行结果

hello: Tony
hi: Pepper
time1: 11ms
time2: 11ms

直接传递lambda函数 

package org.example.a;
 
interface IRun {
    String welcome(String string);
}
 
class Util {
    public static long executionTime(IRun iRun, String string) {
        long startTime = System.currentTimeMillis();
        System.out.println(iRun.welcome(string));
        //本处刻意添加这一无意义延时,防止执行太快返回0
        try {
            Thread.sleep(10);
        } catch (Exception e) {
            System.out.println(e);
        }
        long endTime = System.currentTimeMillis();
        return endTime - startTime;
    }
}
 
public class Demo {
    public static void main(String[] args) {
        long time = Util.executionTime((string -> {
                    String tmp;
                    tmp = "hello: " + string;
                    return tmp;
                })
                , "Tony");
        System.out.println("time: " + time + "ms");
    }
}

执行结果

hello: Tony
time: 11ms

遍历集合

package org.example.a;
 
import java.util.ArrayList;
import java.util.List;
 
public class Demo{
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
 
        //以前的循环方式
        for (String string : list) {
            System.out.println(string);
        }
 
        //使用lambda表达式输出list中的每个值
        list.forEach(c->{
            System.out.println(c);
        });
 
        // 在 Java 8 中使用双冒号操作符(double colon operator)。也属于lamda表达式
        list.forEach(System.out::println);
    }
}

执行结果

aaa
bbb
aaa
bbb
aaa
bbb

创建线程

package org.example.a;
 
public class Demo{
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Anonymous Internal Class !");
            }
        }).start();
 
        new Thread(() -> System.out.println("Lambda !")).start();
    }
}

执行结果

Anonymous Internal Class !
Lambda !

排序

package org.example.a;
 
import java.util.Arrays;
import java.util.Comparator;
 
public class Demo{
    public static void main(String[] args) {
        String[] players = {"Rafael Nadal", "Novak Djokovic", "Stanislas Wawrinka"};
        
        Arrays.sort(players, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return (o1.compareTo(o2));
            }
        });
 
//        Comparator<String> sortByName = (String s1, String s2) -> (s1.compareTo(s2));
//        Arrays.sort(players, sortByName);
        
//        Arrays.sort(players, (String s1, String s2) -> (s1.compareTo(s2)));
        
        for(String string:players){
            System.out.println(string);
        }
    }
}

执行结果(换成注释掉的两种任意一种都是一样的)

Novak Djokovic
Rafael Nadal
Stanislas Wawrinka

The above is the detailed content of How to use Lambda expressions in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

归纳整理JAVA装饰器模式(实例详解)归纳整理JAVA装饰器模式(实例详解)May 05, 2022 pm 06:48 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool