Java 8 Lambda expressions make your code more concise and lambda expressions

Source: Internet
Author: User

Java 8 Lambda expressions make your code more concise and lambda expressions

Lambda expressionsIs a very important new feature of Java 8. Like methods, it uses simple syntax to define the parameter list and method body. Currently, Lambda expressions have become the standard for advanced programming languages, such as Python and Swift.

In the implementation of Java 8, Lambda expressions are essentially a "syntactic Sugar". After being inferred and processed by the compiler, they are converted into regular Java code, therefore, your code can be simpler just as you wrote in the question.

Basic Syntax of Lambda expressions: (parameters)-> expression or (parameters)-> {statements ;}

Lambda expressions are not a method. They can be used to define a code block, and form a Java anonymous internal class. Lambda expressions are usually assigned to a function interface. A function interface is an interface with only one abstract method. Lambda expressions can infer the variable type through the Context Environment. Therefore, we recommend that you do not explicitly specify the variable type during use.

For example, suppose we have a List of the <String> type. to traverse and print the list content, the code before Java 7 is as follows:

1 for (String s : list) {2     System.out.println(s);3 }

 

Java 8:

1 list.forEach((s) -> System.out.println(s));

Or

1 list.forEach(System.out::println);

Let's look at another example. If we want to sort the list, the Java 7 Code is as follows:

1 Collections.sort(list, new Comparator<String>() {2     @Override3     public int compare(String p1, String p2) {4         return p1.compareTo(p2);5     }6 });

Java 8:

1 Collections.sort(list, (String p1, String p2) -> p1.compareTo(p2));

It should be noted that Lambda expressions can be used for parameter type inference. Here we can make full use of this point. The String before the p1 and p2 parameters is not required, so it can be simplified as follows:

1 Collections.sort(list, (p1,p2) -> p1.compareTo(p2));

Further steps:

1 list.sort((p1,p2) -> p1.compareTo(p2));

Is it much simpler :)

Lambda expressions can also be used to replace anonymous classes. For example, to implement the Runnable interface, the Java 7 Code is as follows:

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

 

Java 8:

1 new Thread(() -> System.out.println("Hello world !")).start();

Use Lambda expressions to implement Runnable and convert the five-line code into one line of statements.

Reasonable Use of Lambda expressions not only simplifies several lines of code, but also achieves reasonable code abstraction. When we implement two very large methods, if most of the Code is the same and only a small bit of code is different, we can pass in the Lambda expression as a parameter, to achieve different ideographic purposes.

As mentioned aboveFunction interface (Functional Interfaces)It indicates that there is only one abstract method interface, which can be used to point to a Lambda expression. For example:

1 Consumer c = (s) -> System.out.println(s);

Java 8 implements the following in the java. util. function package:

  • Function <T, R>: accepts a parameter T and returns the result R.

  • Predicate <T>: accept a parameter T and return a boolean value.

  • Supplier <T>: returns the result T if no parameter is accepted.

  • Consumer <T>: accept a parameter T and no result is returned.

  • UnaryOperator <T>: inherits from the Function <T, T>. If a parameter T is accepted, the result of the same type T is returned.

  • BiFunction <T, U, R>: accept two parameters T and U, and return the result R.

  • BinaryOperator <T>: inherits from BiFunction <T, T, T>. Two Parameters of the same type T are accepted and the result of the same type T is returned.

  • ......

In addition, the most familiar functional interfaces include:

  • Runnable: in fact, it does not accept any parameters or return results.

  • Comparable <T>: actually accept two parameters of the same type T, and return int

  • Callable <V>: returns the result V if no parameter is accepted.

Generally, we should try to use standard functional interfaces. If we want to customize them, we can use the @ FunctionalInterface annotation, for example:

1 @FunctionalInterface2 public interface funcInterface {3     public abstract B op(A a);4 }

 

When using a function interface as a parameter, avoid method overloading as much as possible.Since Lambda expressions determine the type of Lambda expressions (that is, Target Typing) based on the Target type in the environment, method overloading sometimes causes the compiler to be dizzy. We can use different method names to solve this problem.

Here, we also need to clarify the following points:

  • Lambda expressions are not functional interfaces. It can be assigned a value to a functional interface because the compiler packs it into a corresponding functional interface;

  • Furthermore, Lambda expressions are not anonymous:

    • It does not define a new scope, and the local variables defined outside are visible inside the Lambda expression;

    • It cannot change the value of external variables. It can only read final or javastively final variables;

    • It cannot read external variables forward, that is, it can only read external variables after they are declared, but can be read in anonymous internal classes;

Java 8 also enhances the batch Stream operation on the set data, which is usually used together with Lambda expressions. Lambda expressions and Stream can be said to be the biggest change since the Java language was added to Generics and annotations. The next article will focus on Stream.

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.