search
HomeJavajavaTutorialJava Lambda expression example analysis

    1. Introduction

    First of all, Lambda expression is a new feature of Java8. It provides support for functional programming in Java programming and helps The simplicity of the code can replace most of the anonymous functions, especially for collection traversal and collection operations, which greatly simplifies the code.

    The body of the Lambda expression:

    Java Lambda expression example analysis

    Functional interface:

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

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

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

    2. If @FunctionalInterface is not added **Note, if you write only one abstract method in the interface, it can also be considered as a functional interface:

    public interface MyInteface {
        void eat();
    }

    This is also possible.

    3. There is only one case where functional interfaces do not only have abstract methods, that is, they can inherit the methods of the Object class:

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

    2. The 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 methods with parameters

    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("肉");
        }
    }

    // Output: Students are eating meat

    3. Lambda expressions to implement multi-threading

    The method of creating multi-threads was introduced in the article on multi-threading (1). 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 operations

    We use lambda to operate operations and can save a lot of 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 rewrite the interface methods to achieve specific implementation. If we have existing methods that can be implemented, we can also refer to existing methods through method references to make the methods in the interface specific. The advantage of this implementation 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 expressions for collections Using

    Of course Lambda is also very convenient to operate collections, and you 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 Java Lambda expression example analysis. 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 Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

    JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

    What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

    Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

    Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

    The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

    Is Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksIs Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksMay 13, 2025 am 12:03 AM

    JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

    Demystifying the JVM: Your Key to Understanding Java ExecutionDemystifying the JVM: Your Key to Understanding Java ExecutionMay 13, 2025 am 12:02 AM

    TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

    Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

    Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

    What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

    Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

    Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

    The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

    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 Article

    Hot Tools

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    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.