search
HomeJavajavaTutorialWhat are the uses of Lambda expressions in Java?

    Lambda expression:

    1. Introduction

    First of all, Lambda expression belongs toJava8 A new feature of provides support for functional programming in Java programming, which helps to simplify the code and can replace most of the anonymous functions. Especially for collection traversal and collection operations, it greatly simplifies the code. .

    The body of the Lambda expression:

    What are the uses of Lambda expressions in Java?

    ##Functional interface:

    Note: Lambda expressions must be used with functional interfaces. The so-called functional interface is an interface with only one abstract method in the interface. It is a functional interface. We can customize it. JDK also has a large number of built-in functions. interface.

    1. @FunctionalInterface annotation modifies the interface, then this interface is a functional interface, which can only have one method. The following is a functional interface:

    @FunctionalInterface
    public interface MyInteface {
        void eat();
    }

    2, If you do not add the @FunctionalInterface** annotation, you can also think of it as a functional interface if you only write an abstract method in the interface:

    public interface MyInteface {
        void eat();
    }

    This is also possible.

    3, Functional interface only has one situation where does not only have abstract methods, that is, methods that can inherit the Object class:

    @FunctionalInterface
    public interface MyInteface3 {
        void eat();
        @Override
        String toString();
        @Override
        int hashCode();
    }

    2, Use of Lambda expressions:

    1. Use in ordinary methods

    Student class:

    @FunctionalInterface
    public interface Student {
        void eat();
    }

    Test class:

    public class Test {
        public static void main(String[] args) {
            Student stu = new Student() {
                //普通方法,重写并使用
                @Override
                public void eat() {
                    System.out.println("我是学生");
                }
            };
            stu.eat();
    
            //lambda表达式写法:
            //参数1:重写了Student接口中唯一的那个无参数的eat抽象方法做了具体的实现,所以重写不 需要署名
            //参数2:-> 表达式 固定的
            //参数3:{具体的实现} 对Student接口中唯一的eat方法做了具体的实现
                Student stu2 = () -> {
                    System.out.println("学生吃饭");
                };
            stu2.eat();
        }
    }

    Output:

    I am a student

    Students eat

    2. Use of parameter method

    Student class:

    @FunctionalInterface
    public interface Student {
        void eat(String food);
    }

    Test class:

    public class Test {
        public static void main(String[] args) {
            //lambda重写Student接口唯一的有参方法:
            Student stu2 = (foodName)->{
                System.out.println("学生在吃"+foodName);
            };
            stu2.eat("肉");
        }
    }
    //输出:学生在吃肉

    3. Lambda expression to implement multi-threading

    In the previous article on multi-threading (1), the method of creating multi-threads was introduced. Here we use lambda to create threads:

    public class Test {
        public static void main(String[] args) {
            Thread t = new Thread(() -> {
                System.out.println("这个线程是由lambda来创建的");
            });
            t.start();
        }
    }

    4. Lambda expression operation operation

    We can use lambda to operate with a lot less code:

    Functional interface:

    @FunctionalInterface
    public interface Calculator<T> {
        T operation(T v1,T v2);
    }

    Test class:

    public class Test {
        //计算方法
        public static Integer operator(Integer v1,Integer v2,Calculator<Integer> calculator){
            return calculator.operation(v1, v2);
        }
        public static void main(String[] args) {
    
            //使用lambda表达式:
            //这里的意思就是传入两个参数,返回运行后的值
            int add = Test.operator(5,10,(x,y)->{
                return x+y;
            });
    
            //简写:可以少写很多代码,比上面更简介了
            int num1 = Test.operator(5,10,(x,y)->x+y);
            int num2 = Test.operator(10,5,(x,y)->x-y);
            System.out.println(add);
            System.out.println(num1);
            System.out.println(num2);
        }
    }

    Output:

    15, 15, 5

    5, Lambda expression method reference

    Sometimes we don’t have to To rewrite the methods of the interface for specific implementation, if we have existing methods that can be implemented, we can also refer to the existing methods through method references to implement specific implementations of the methods in the interface. The advantage of this is code reuse. , such as the following:

    Functional interface:

    public interface ResultOneParam {
        int method(int a);
    }

    Test class:

    public class Test {
        public int addTo(int a){
            return  a+10;
        }
        public  static int addTo2(int a){
            return  a+10;
        }
        public static void main(String[] args) {
            //lambda重写了method方法
            ResultOneParam lambda1=(a)->a+10;
            //方法引用:就是在Test里面的addTo2方法用来替代method被重写的方法
            ResultOneParam lambda2= Test::addTo2;
            int result1= lambda2.method(9);
            System.out.println(result1);
            //方法引用 ::引用现成的方法来替代方法重写,这样可以方法重用
            Test test=new Test();
            ResultOneParam lambda3=test::addTo;
            int result2= lambda3.method(9);
            System.out.println(result1);
        }
    }

    6. Lambda expression pair The use of collections

    Of course Lambda is also very convenient to operate collections, which can save a lot of code:

    public class Test {
        public static void main(String[] args) {
            List<Integer> list = Arrays.asList(5,1,3,4,5,0,9,7,0,1,5);
            //lambda表达式遍历集合,重写了Consumer接口的方法
            list.forEach((element)->{
                System.out.println(element);
            });
            //简写:
            list.forEach(element-> System.out.println(element));
            //lambda表达式方法引用,用于遍历输出list集合:
            list.forEach(System.out::print);
            //输出list的偶数:
            list.forEach(element->{
                if(element%2==0){
                    System.out.println(element);
                }
            });
        }
    }

    The above is the detailed content of What are the uses of 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
    Are there any emerging technologies that threaten or enhance Java's platform independence?Are there any emerging technologies that threaten or enhance Java's platform independence?Apr 24, 2025 am 12:11 AM

    Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages ​​for performance.

    What are the different implementations of the JVM, and do they all provide the same level of platform independence?What are the different implementations of the JVM, and do they all provide the same level of platform independence?Apr 24, 2025 am 12:10 AM

    Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages ​​and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

    How does platform independence reduce development costs and time?How does platform independence reduce development costs and time?Apr 24, 2025 am 12:08 AM

    Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.

    How does Java's platform independence facilitate code reuse?How does Java's platform independence facilitate code reuse?Apr 24, 2025 am 12:05 AM

    Java'splatformindependencefacilitatescodereusebyallowingbytecodetorunonanyplatformwithaJVM.1)Developerscanwritecodeonceforconsistentbehavioracrossplatforms.2)Maintenanceisreducedascodedoesn'tneedrewriting.3)Librariesandframeworkscanbesharedacrossproj

    How do you troubleshoot platform-specific issues in a Java application?How do you troubleshoot platform-specific issues in a Java application?Apr 24, 2025 am 12:04 AM

    To solve platform-specific problems in Java applications, you can take the following steps: 1. Use Java's System class to view system properties to understand the running environment. 2. Use the File class or java.nio.file package to process file paths. 3. Load the local library according to operating system conditions. 4. Use VisualVM or JProfiler to optimize cross-platform performance. 5. Ensure that the test environment is consistent with the production environment through Docker containerization. 6. Use GitHubActions to perform automated testing on multiple platforms. These methods help to effectively solve platform-specific problems in Java applications.

    How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

    The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

    Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

    The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

    How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

    Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

    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

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    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.

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.