Chapter 1 lambda expressions

Source: Internet
Author: User
1.1 why Lambdas?

When you operate multiple threads, you will put the code to be processed in the run () function as follows:

class Worker implements Runnable {    public void run() {        for (int i = 0; i < 1000; i++)              doWork();      }    ...}

Then, when you want to execute this code, you need to construct a worker instance to execute it. You can put it into the thread pool or simply process it to start a thread:

Worker w = new Worker();new Thread(w).start();

The focus of this Code is to put the logic you want to process into the run () method.

Another scenario is custom sorting. If you do not want to sort by dictionary by default, but want to sort by string length, you need to sort by a comparator object:

class LengthComparator implements Comparator<String> {    public int compare(String first, String second) {        return Integer.Compare(first.length(), second.length());    }}Arrays.sort(strings, new LengthComparator());

The sort function always calls the compare method to ensure that the array is re-sorted by length.

 

 

NOTE: If X. Equals (y) in integer. Compare (X, Y) is = true, 0 is returned. If x <Y, a negative number is returned, and x> Y returns a positive number. This static method has been added to Java 7. Do not calculate x-y and compare it with X or Y, because x-y may overflow.

Another scenario is button callback. You put the callback processing in the listener interface function of the implementation, construct an instance, and register the instance to the button:
button.setOnAction(new EventHandler<ActionEvent>) {    public void handle(ActionEvent event) {        System.out.println("Thanks for clicking");      }});

When this button is clicked, the handle method is executed.

From the above examples, you can see that these operations require a large segment of code to process. Such complex processing is not easily understood by everyone. Therefore, a very important feature added to Java 8 is lambda expressions.

1.2 Lambda expression syntax

Now let's take a look at the previous sorting example:

Integer.compare(first.length(), second.length());

Both first and second are string arrays, and Java is a strongly typed language, so we must handle it like this:

(String first, String second)    -> Integer.compare(first.length(), second.length());

This is your first Lambda expression! This expression is very simple.

As you can see, the lambda expression contains the-> symbol. If this Code cannot be displayed using a simple expression, we can use {} to encapsulate a piece of code, for example:

(String first, String second) -> {    if (first.length() < second.length()) return -1;    else if (first.length() > second.length()) return 1;    else return 0;}

When a Lambda expression has no parameters, we can do this:

() -> { for (int i = 0; i < 1000; i++) doWorker(); }

If a parameter in a Lambda expression can infer its type, we can also do this:

Comparator <string> comp = (first, second) // equivalent to (string first, string second)-> integer. compare (first. length (), second. length ());

 

 

You can add the annotation or final modifier to the lambda expression parameters:

(Final string name)->...

(@ Nonnull string name)->...

 

We have never mentioned the return type in lambda expressions because it can be inferred in the lambda context, for example:

(String first, string second)-> integer. Compare (first. Length (), second. Length ())

From this we can see that the return type is int.

1.3 functional interfaces

Java already encapsulates some existing interface code and wants to runnable and comparator. Lambda is backward compatible with these interfaces.

When a single-instance abstract method interface object can be displayed using a Lambda expression, we call this interface a functional interface.

To demonstrate functional interfaces, let's take a look at the arrays. Sort () method. Its second parameter requires a comparator instance. You can use Lambda to do this:

Arrays.sort(words,    (first, second) -> Integer.compare(first.length(), second.length()));

Compared with traditional internal classes, lambda expressions can efficiently complete it. Lambda expressions are best understood as a function rather than an object.

Lambda syntax is very short and simple. Let's take another example:

button.setOnAction(event ->    System.out.println("Thanks for clicking")); 

Compared with internal classes, it significantly improves readability.

In fact, in Java, you can only apply lambda expressions to functional interfaces.

Java API defines some common functional interfaces in Java. util. function. For example, bifunction <t, u, r>, this interface uses the parameter types T and U to return the type R. We can apply it in the example just now:

BiFunction<String, String, Integer> comp    = (first, second) -> Integer.compare(first.length(), second.length());

Of course, only a comparator is constructed here and can be sorted only when the arrays. sort method is called.

1.4 method reference

Sometimes, you have to add unnecessary code to a method. For example, if you want to print the event object after a button is clicked:

button.setOnAction(event->System.out.println(event));

It would be nice if you can only use the println method, for example:

button.setOnAction(System.out::println);

The system. Out: println expression is a method reference. It is equivalent to X-> system. Out. println (X ).

For example, we want to sort the array with case-insensitive values:

Arrays.sort(strings, String::compareToIgnoreCase);

In these examples, the rule of: operator is:

  • Object: instancemethod
  • Class: staticmethod
  • Class: instancemethod

In the first two examples, a method reference is equivalent to a function parameter in a Lambda expression. out: println is equivalent to X-> system. out. println (x), corresponding, Math: pow is equivalent to (x, y)-> math. pow (x, y ).

In the third example, the first parameter becomes the function object. String: comparetoignorecase is equivalent to (x, y)-> X. comparetoignorecase (y ).

You can also use this, for example: this: equals is equivalent to X-> This. Equals (x). Of course, you can also use super.

Super: instancemethod

For example:

class Greeter {    public void greet() {        System.out.println("Hello world");    }}class ConcurrentGreeter extends Greeter {    public void greet() {        Thread t = new Thread(super::greet);        t.start();    }}
1.5 construct reference

In addition to the new method, construct references similar to method references. For example, button: New is a button constructor.

List<String> labels = ...;Stream<Button> stream = labels.stream().map(Button::new);List<Button> buttons = stream.collect(Collections.toList());
1.6 variable Fields

When you want to get variables from a closure function or class in Lambda, the following code is displayed:

public static void repeatMessage(String text, int count) {    Runnable r = () -> {        for (int i = 0; i < count; i++) {            System.out.println(text);            Thread.yield();        }    };    new Thread(r).start();}

 

1.7 default method

To be continued

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.