Java 8 Lambda expressions

Source: Internet
Author: User
Tags stream api

Java 8 Lambda expressions

Lambda expressions are essentially an anonymous function. C #3.0 introduces Lambda expressions, and Java 8 is not weak. Java 8 has been released for a long time. Today, JDK is installed to experience the Lambda expression in Java 8.

First, let's look at an example that does not apply to Lambda expressions.
For example, we want to sort a group of strings.

public class Hello {    public static void main(String[] args) {        List
  
    names = Arrays.asList("Tan", "Zhen", "Yu");        Collections.sort(names, new Comparator
   
    () {            @Override            public int compare(String a, String b) {                return a.compareTo(b);            }        });        for (String name : names) {            System.out.println(name);        }    }}
   
  

Running result:

TanYuZhen

Take a look at the code using Lambda expressions in the same example:

public class Hello {    public static void main(String[] args) {        List
  
    names = Arrays.asList("Tan", "Zhen", "Yu");        Collections.sort(names, (String a, String b) -> a.compareTo(b));        Stream
   
     stream = names.stream();        stream.forEach(System.out::println);    }}
   
  

Is it concise.

The following describes the Lambda expressions in Java 8 in detail.
(String a, String B)-> a. compareTo (B) is a Lambda expression. The parameter list of the function is enclosed in brackets, and the-> symbol is followed by the function body. Therefore, Lambda uses parentheses to list function parameters, and then points to the function body with the-> symbol. The function body is usually enclosed by curly brackets.
The preceding function is a. compareTo (B. The complete statement should be:

(String a, String b) -> {    returen a.compareTo(b);}

Because there is only one sentence in the function body, braces and return keywords can be omitted.

In Java, each Lambda expression corresponds to a type, usually an interface type, which is annotated using @ FunctionalInterface. This "functional interface" refers to an interface that only contains an abstract method. Each Lambda expression of this type will be matched with this abstract method. That is to say, each Lambda expression corresponds to the abstract method in the functional interface.
In addition, Java 8 allows us to add a non-abstract method implementation to the interface. We only need to use the default keyword. This feature is also called an extension method ,. Therefore, function interfaces can only have one abstract method, while others can only be extension methods. The following is the Comparator interface in Java 8. compare is an abstract method. In addition, there are some extension methods.

@FunctionalInterfacepublic interface Comparator {     int compare(T o1, T o2);    ......}


In the preceding sample code, stream. forEach (System. out: println) is used to output each string using Stream API. The following is a detailed explanation.
Java 8 introduces a new Stream API. The Stream here is different from the I/O Stream. It is more like a collection class with Iterable, but its behavior and collection class are different. Stream API is introduced to make up for Java functional programming defects. For many languages that support functional programming, map () and reduce () are basically built into the language's standard library (such as Python and JavaScript ).
There are many ways to create a Stream. The simplest way is to convert a Collection into a Stream, like the Stream above. Stream = names. stream ().
The stream () method added to the Collection class is used to convert a set into a Stream. Then, Stream transformation is realized through filter (), map (), and so on. Stream also has a forEach () to complete iteration of each element.

This is the signature void forEach (Consumer Action ). Consumer It is also a functional interface, so we should pass in a function.
Java 8 allows you to use the: keyword to pass the method or constructor reference. For example, the above System. out: println is a reference to the println function. If you reference a constructor, you can use the form of object: new.

I personally feel that the function interface in Java 8 is similar to the proxy type (delegate) in C.

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.