What is a Lambda expression

A Lambda expression is an anonymous function named after the λ calculus in mathematics. Simply put, it is an undeclared method: it has no name, but it has a list of arguments, a method body, a return type, and possibly an exception that can be thrown.

It allows for cleaner, more flexible code. As a more compact code style, the expressiveness of the Java language has been improved.

For example, a List of peopleList with People objects needs to be sorted by age. Before:

<People> Comparator = new Comparator<People>() {@override public int compare(People o1); People o2) { if (o1.getAge() > o2.getAge()) { return 1; } else { return -1; }}}; // sort collections.sort (peopleList, comparator);Copy the code

After JDK1.8, use Lambda expressions:

// Lambda <People> Comparator = (o1, o2) -> {if (o1.getage () > o2.getage ()) {return 1; } else { return -1; }}; // sort collections.sort (peopleList, comparator);Copy the code

I have to admit that the code is cleaner and simpler!

In fact, a more concise way to write this is:

peopleList.sort(Comparator.comparingInt(People::getAge));
Copy the code

2. Lambda expression syntax

The syntax of a Lambda expression is as follows:

(parameters) -> expression



(parameters) ->{ statements; }

Among them:

  • Optional type declaration: There is no need to declare parameter types, and the compiler can uniformly identify parameter values.
  • Optional parameter parentheses: You do not need to define parentheses for one parameter, but you need to define parentheses for multiple parameters.
  • Optional braces: If the body contains a statement, braces are not required.
  • Optional return keyword: The compiler automatically returns the value if the body has only one expression return value. Curly braces are required to specify that the expression returns a value.

Grammar is simple and you’ll love it when you learn to use it!

3. Examples of Lambda expressions

A simple example is as follows:

// 1. No arguments, return value 5 () -> 5 // 2. Take an argument (numeric type) and return twice its value x -> 2 * x // 3. Take two arguments (numbers) and return their difference (x, y) -> x -- y // 4. Accept 2 int integers and return their sum (int x, int y) -> x + y Take a string object and print it on the console without returning any value (looks like returning void) (string s) -> system.out.print (s)Copy the code

Usage Scenarios:

Usage scenarios Example Lambda expressions
Boolean expression (List list) -> list.isEmpty()
Create an object () -> new People(10)
Consuming an object (People p) -> {System.out.println(p.getAge()); }
Select/extract from an object (int i) -> i.getAge()
Combine two values (int a, int b) -> a * b
Compare two objects (People p1, People p2) -> p1.getAge().compareTo(p2.getAge())

Examples are as follows:

/** * set operation. For (People People: peopleList) {system.out.print (people.getName()); Peoplelist.foreach (people -> system.out.print (people.getName())); peoplelist.foreach (people -> system.out.print (people.getName()))); New Thread(new Runnable() {@override public void run() { System.out.println(Thread.currentThread().getName()); } }).start(); // Lambda expression new Thread(() -> system.out.println (thread.currentThread ().getName())).start(); ...Copy the code

For JDK1.8 new features, in IDEA is also highly recommended. Where Lambda expressions can be used, IDEA will gray out the corresponding codes and mark them as wavy lines to give suggestions. We can use the shortcut Alt + Enter to automatically replace them with Lambda expressions, isn’t it great?

4, summarize

Now that you’ve gotten to know Lambda expressions, it’s a lot simpler, or at least a lot simpler (with some performance improvements as well).

Lambda expressions will continue to be common when we learn about the new JDK1.8 features. The syntax is simple, but you need to use it more often to get the most out of it. Think about Lambda expressions in your daily development, and you’ll soon get comfortable with them and love them more.