Awesome lambda expression, Java Party use up! (Most simple lambda tutorial)

Source: Internet
Author: User

When I accidentally saw the HelloWorld tutorial of Lambda when I brushed my microblog, I thought it was cool! Share a bit!

Examples of effects

The overall look is code simplicity, as follows

//之前的写法btn.setOnClickListener(new View.OnClickListener() {     @Override      publicvoidonClick(View v) {          System.out.println("hello lambda");          ...      }});//Lambda表达式写法btn.setsetOnClickListener((View v) -> {          System.out.println("hello lambda");          ...      });
//之前的写法new Thread(new Runnable() {    @Override     publicvoidrun() {         System.out.println("hello lambda");     }}).start();//Lambda表达式写法(只有一行内容可以去掉代码块大括号)new Thread(() -> System.out.println("hello lambda")).start();
Lambda expression templates
(T args) -> {    //代码块}

A lambda expression consists of three parts:
-Parameter: (T args) is the parameter part of this lambda expression, including the parameter type and parameter name, which can be empty and the parentheses indispensable
-Arrows:->, indispensable
-code block: The code that is included with "{}". Curly braces can be omitted when the code inside the code block is only one line, and the semicolon in the code block is omitted

Principle

The lambda expression is not a new syntax, it is a streamlined literal, in fact the programmer can omit the "certain" work in the anonymous inner class, and then the JVM restores the simplified expression by derivation.

In-step instruction
//对比两个学生的年龄publicvoidsort(Student[] students) {    new Comparator<Student>() {        @Override        publicintcompare(Student stu1, Student stu2) {            return Integer.compare(stu1.age, stu2.age);        }    });}

As the example above, the second parameter "must" to be a new Comparator<T>(){} type, then you can first remove the first "must"

//对比两个学生的年龄publicvoidsort(Student[] students) {    Arrays.sort(students,        @Override        publicintcompare(Student stu1, Student stu2) {            return Integer.compare(stu1.age, stu2.age);        }    );}

new Comparator<T>(){}"Must" to override the compare method, and "must" return the int type, then the method name can also be removed

//对比两个学生的年龄publicvoidsort(Student[] students) {    Arrays.sort(students,        (Student stu1, Student stu2) {            return Integer.compare(stu1.age, stu2.age);        }    );}

This time it will still be an error, we have the parameter list and the code block with arrows (-) to form a complete lambda expression can be compiled through.

//对比两个学生的年龄publicvoidsort(Student[] students) {    Arrays.sort(students,        (Student stu1, Student stu2) -> {            return Integer.compare(stu1.age, stu2.age);        }    );}

If there is only one line of code in the code block, you can remove the curly brace and return it (because the compare method must return int), and the last semicolon of the line is removed. and the extra empty rows can be merged into one row.

//对比两个学生的年龄publicvoidsort(Student[] students) {    Arrays.sort(students, (Student stu1, Student stu2) -> Integer.compare(stu1.age, stu2.age));}

compareThe parameter type "must" in the parameter list of the method is the type of the Arrays.sort() first parameter in the method, so it can be omitted because the JVM can help us derive it.

//对比两个学生的年龄publicvoidsort(Student[] students) {    Arrays.sort(students, (stu1, stu2) -> Integer.compare(stu1.age, stu2.age));}

Simplify the finish! Now compare the simplified and simplified code before you feel

//对比两个学生的年龄publicvoidsort(Student[] students) {    //简化前    new Comparator<Student>() {        @Override        publicintcompare(Student stu1, Student stu2) {            return Integer.compare(stu1.age, stu2.age);        }    });    //简化后    Arrays.sort(students, (stu1, stu2) -> Integer.compare(stu1.age, stu2.age));}
Other effects

Lambda expressions can also be used to assign values.

r = () -> System.out.println("hello lambda");new Thread(r).start();
Lambda Usage Qualification

Simply put, downloading the latest eclipse will support lambda syntax.

I am the Android party, Java 8 above support lambda expression, and Android only support Java 7, if you want to use Android, use the Gradle-retrolambda plugin.

Finally, we recommend you to watch the video: "Lambda's HelloWorld video tutorial"

Reference:
HelloWorld Video tutorial on Lambda
"Java 8 Lambda and its application in Android development"
"How to use lambda expressions in Android Programming"

Copyright NOTICE: This article is for bloggers original article, reprint please indicate the original address and author (Ahan).

Awesome lambda expression, Java Party use up! (Most simple lambda tutorial)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.