New Features of JDK 8-Lambda expressions and new features of JDK 8 lambda

Source: Internet
Author: User

New Features of JDK 8-Lambda expressions and new features of JDK 8 lambda

JDK 8 has been released for nearly four years. It seems a little out of date to talk about its new features ". Although JDK8 is no longer "new", Lambda expressions, one of its important features, are still not used by most developers or even well-known.

As we all know in the development environment in China, there are various old projects and various release risks, which often discouraged the company and project team from new technologies, some companies are still using JDK6 for project development today, which leads to great restrictions on the selection of many technologies, in this way, we cannot follow the footsteps of the times to make projects and even companies decline step by step.

This article briefly introduces Lambda expressions, one of the important new features of JDK 8. Before JDK 8, Java did not support functional programming. The so-called function programming can be understood as passing a function (also known as "behavior") as a parameter. We usually mention object-oriented programming, which is an abstraction of data (various POJO classes ), functional programming is the abstraction of behavior (passing behavior as a parameter ). This is a common syntax feature in JavaScript, but it does not work to pass a function as a parameter in Java. Fortunately, the emergence of JDK 8 breaks this restriction in Java.

 

Lambda expressions

  First, let's introduce an example. I don't know if I have any experience writing code in IDEA. If I write a thread according to the traditional Java syntax rules in the JDK8 environment as follows.

1 new Thread(new Runnable() {2     @Override3     public void run() {4         System.out.println("Hello World!");5     }6 });

IDEA will prompt you to use Lambda expressions to replace them.

To use Lambda expressions, you only need to use one sentence to replace the above Anonymous class method.

new Thread(() -> System.out.println("Hello World!"));

In this example, the traditional syntax rule is to pass an anonymous internal class as a parameter. we implement the Runnable interface and pass it as a parameter to the Thread class, in fact, we pass a piece of code, that is, we pass the code as data, which leads to a lot of unnecessary "Sample Code ".

Lambda expressions are composed of three parts:

In the following example, we will explain this structure in detail, including the existence of parameters and returned values. So what exactly does this strange and strange syntax rule look like in Java? This is also a problem that bothers me. When can I use Lambda expressions in what scenarios.

  The parameter type that can receive Lambda expressions. It is an interface that contains only one method.The interface that contains only one method is called"Function Interface".

For example, in the preceding example of creating a thread, the Runnable interface contains only one method, so it is called a "function interface". Therefore, it can use Lambad expressions to replace anonymous internal classes. According to this rule, we try to write a function interface and use Lambda expressions as parameters for passing.

1 package com. coderbuff. custom; 2 3/** 4 * function interface: there is only one method interface. Type 5 * Created by Kevin on 2018/2/17. 6 */7 public interface FunctionInterface {8 void test (); 9} As a Lambda expression}

Test:

1 package com. coderbuff. custom; 2 3 import org. junit. test; 4 5/** 6 * function Interface Test 7 * Created by Kevin on 2018/2/17. 8 */9 public class FunctionInterfaceTest {10 11 @ Test12 public void testLambda () {13 func (new FunctionInterface () {14 @ Override15 public void test () {16 System. out. println ("Hello World! "); 17} 18}); 19 // use a Lambda expression to replace the above anonymous internal class 20 func (()-> System. out. println ("Hello World")); 21} 22 23 private void func (FunctionInterface functionInterface) {24 functionInterface. test (); 25} 26}

As you can see, a Lambda expression can be used as long as an interface contains only one method. Such an interface is called a "function interface ".

The above function interface is relatively simpleDoes not contain parameters or return values..

Let's modify the FunctionInterface function interface to gradually increase the difficulty of Lambda expressions --Contains parameters, not returned values.

1 package com. coderbuff. custom; 2 3/** 4 * function interface: there is only one method interface. Type 5 * Created by Kevin on 2018/2/17. 6 */7 public interface FunctionInterface {8 void test (int param); 9}

Test:

1 package com. coderbuff. custom; 2 3 import org. junit. test; 4 5/** 6 * function Interface Test 7 * Created by Kevin on 2018/2/17. 8 */9 public class FunctionInterfaceTest {10 11 @ Test12 public void testLambda () {13 // use Lambda expressions to replace anonymous internal class 14 func ((X)-> System. out. println ("Hello World" +X)); 15} 16 17 private void func (FunctionInterface functionInterface) {18 int x = 1; 19 functionInterface. test (x); 20} 21}

Follow the Lambda expression "(x)-> Sysout. out. println ("Hello World" + x) ", the parameter is passed on the left. The parameter type is not specified here, because it can be type deduced through context, however, in some cases, you cannot export the parameter type (usually the IDE will prompt that it cannot be deduced during compilation). In this case, you need to specify the parameter type.I personally suggest specifying the parameter type of the function in any case.

In which case cannot we export the parameter type? That is, when the function interface is a generic type.

1 package com. coderbuff. custom; 2 3/** 4 * function interface: there is only one method interface. 5 * Created by Kevin on 2018/2/17. 6 */7 public interface FunctionInterface <T> {8 void test (T param); 9}

Test:

1 package com. coderbuff. custom; 2 3 import org. junit. test; 4 5/** 6 * function Interface Test 7 * Created by Kevin on 2018/2/17. 8 */9 public class FunctionInterfaceTest {10 11 @ Test12 public void testLambda () {13 // use Lambda expressions to replace anonymous internal class 14 func ((Integer x)-> System. out. println ("Hello World" +X)); 15} 16 17 private void func (FunctionInterface <Integer> functionInterface) {18 int x = 1; 19 functionInterface. test (x); 20} 21}

The above example mentions two situations of Lambda expressions:

  No parameter, no return value;

There are parameters and no return values.

NextParameters and returned valuesThis is a complicated situation.

1 package com. coderbuff. custom; 2 3/** 4 * function interface: there is only one method interface. Type 5 * Created by Kevin on 2018/2/17. 6 */7 public interface FunctionInterface <T> {8 boolean test (T param); 9}

Test:

1 package com. coderbuff. custom; 2 3 import org. junit. test; 4 5/** 6 * function Interface Test 7 * Created by Kevin on 2018/2/17. 8 */9 public class FunctionInterfaceTest {10 11 @ Test12 public void testLambda () {13 // use Lambda expressions to replace anonymous internal class 14 func ((Integer x)-> true); 15} 16 17 private void func (FunctionInterface <Integer> functionInterface) {18 int x = 1; 19 functionInterface. test (x); 20} 21}

In this case, the Lambda expression "(Integer x)-> true" is displayed, and the body of the expression is displayed on the right. true is returned directly. If there are multiple lines of code, brackets can be used directly. For example:

func((Integer x) -> {    System.out.println("Hello World" + x);    return true;});

Basic syntax rules of Lambda expressions:

No parameter, no return value;

There are parameters and no return values;

There are parameters and return values.

These three basic situations have been clarified, especially when Lambda expressions can be used to replace anonymous internal classes. That is, the Application Scenario of Lambda expressions is function interfaces. The new feature of Lambda expressions is introduced in JDK 8. The greater benefit is the collection of API updates, the newly added Stream class library, so that we do not use the for loop as we used in traversal.

 

JDK8 uses the correct set posture

Example: calculate the number of students from "chengdu.

Code before JDK 8:

for (Student student : studentList) {    if (student.getCity().equals("chengdu")) {        count++;    }}

JDK8 uses the correct set posture:

count = studentList.stream().filter((student -> student.getCity().equals("chengdu"))).count();

The "difficulty" of using APIs seems to have improved, but it is actually just unfamiliar. The traditional iteration method requires reading a complete loop to understand the code logic. The JDK8 method can be meaningful and the amount of code is greatly reduced.

The most important one is Stream. Stream is a tool that implements complex operations on the Collection class through functional programming. If you want to explain in detail the implementation method of Stream, I believe that it is not enough to write a blog, so we will not examine the internal implementation of Stream here. I would like to tell you that if you are lucky enough to use the JDK8 development environment for development, try to learn how to use a new set of Operation APIs.

Previously, Lambda expressions and functional programming were just to the point of "Understanding". It seems that they just felt that the amount of code was reduced, this article does not have a deep understanding of the Lambda style. More is to pave the way for more knowledge or serve as a literacy post. There are too many Lambda expressions to be applied, concurrent Programming and responsive programming. If you have better ideas about Lambda expressions or functional programming, leave a comment.

 

 

This is a public number that can add buff to programmers.

Related Article

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.