Wechat search “program ape Alang” focus on me, a technical tool man. Like and see, unlimited power.

This article Github.com/niumoo/Java… And program ape Alang blog has been included, there are many knowledge points and series of articles.

Current date: November 11, 2019, how many days are there until the RELEASE of JDK 14 (March 17, 2020)?

// How many days until JDK 14 is released?
LocalDate jdk14 = LocalDate.of(2020.3.17);
LocalDate nowDate = LocalDate.now();
System.out.println("JDK 14 release date:"+nowDate.until(jdk14,ChronoUnit.DAYS)+"Day");
Copy the code

1. Introduction

Java 8 was released on March 18, 2014, and there is no doubt that Java 8 is a major release update for Java, including more than a dozen new features for languages, libraries, tools, JVMS, and more. For example, it provides language-level anonymous functions, expression syntax officially known as Lambda (also known as closures, and the introduction of Lambda also makes streaming operations possible, reducing the complexity of writing code), such as functional interfaces, method references, and repeated annotations. Another example is Optional to prevent null Pointers, Stearm streaming operation, LocalDateTime time operation, etc.

Some of the new Java 8 features have been introduced in previous articles.

  1. Jdk14 will be out, Jdk8 time processing posture is not known?

  2. Can’t use Optional grace to handle null Pointers in Jdk14?

This time, I will introduce Lambda.

2. Lambda is introduced

Lambda derives its name from the eleventh letter Lambda in the Greek alphabet, capitalized as λ and given the English name Lambda. In Java, Lambda expression is an anonymous function. When writing a Lambda in Java, you will find that not only does the Lambda have no function name, but sometimes even the input parameter and return can be omitted, which also makes the code more compact.

3. Function interface introduction

Lambda expressions. Why are functions interfaces introduced? In fact, Java function interfaces can be implicitly converted into Lambda expressions when used. In Java 8, many interfaces have been declared as function interfaces, such as Runnable, Callable, Comparator, etc.

For an example of the function interface, see the Runnable source code in Java 8 (without comments).

package java.lang;

@FunctionalInterface
public interface Runnable {
    public abstract void run(a);
}
Copy the code

So what is a functional interface? There is a very simple definition of an interface that has only one abstract function. The function interface is declared using the @functionalInterface annotation (the annotation declaration is not required; if there is no annotation, there is only one abstract function and it is still considered a function interface). One more or one less abstract function cannot be defined as a function interface, and the compiler will reject compilation if more than one abstract function is used with the function interface annotation. Function interfaces can be implicitly converted to Lambda expressions when used.

Many of the function interface definitions in Java 8, which have many different functions, are included in the java.util.function package. Here are some descriptions of the functions’ interfaces in Java 8.

The serial number Interface & Description
BiConsumer Represents an operation that takes two input parameters and returns no results
BiFunction Represents a method that takes two input parameters and returns a result
BinaryOperator Represents an operation that operates on two operators of the same type and returns the result of the operator of the same type
BiPredicate Represents a two-parameter Boolean method
BooleanSupplier Represents the provider of the Boolean result
Consumer Represents an operation that takes an input parameter and returns nothing
DoubleBinaryOperator Represents operations that operate on two double-valued operators and return the result of a double.
DoubleConsumer Represents an operation that takes a double and returns no result.
DoubleFunction Represents a method that takes a double and returns the result
DoublePredicate Represents a Boolean method with a double value argument
DoubleSupplier Represents the provider of a double value structure
DoubleToIntFunction Takes an input of type double and returns an int.
DoubleToLongFunction Takes a double and returns a long
DoubleUnaryOperator Accepts an argument of type double and returns a value of type double.
Function Takes an input parameter and returns a result.
IntBinaryOperator Accepts two arguments of type int and returns a value of type int.
IntConsumer Takes an input parameter of type int, with no return value.
IntFunction Takes an input parameter of type int and returns a result.
IntPredicate Takes an int input parameter and returns the result of a Boolean value.
IntSupplier Returns a result of type int without arguments.
IntToDoubleFunction Takes an int and returns a double.
IntToLongFunction Takes an int input and returns a long result.
IntUnaryOperator Accepts a parameter of type int and returns a value of type int.
LongBinaryOperator Takes two arguments of type long and returns a value of type long.
LongConsumer Takes an input parameter of type long, with no return value.
LongFunction Takes an input parameter of type long and returns a result.
LongPredicate Takes a long input parameter and returns a boolean-type result.
LongSupplier Returns a value of type long as a result.
LongToDoubleFunction Takes a long input and returns a double result.
LongToIntFunction Takes a long input and returns an int result.
LongUnaryOperator Takes an argument of type long and returns a value of type long.
ObjDoubleConsumer Takes an input parameter of type Object and type double, with no return value.
ObjIntConsumer Takes an input parameter of type object and an int, with no return value.
ObjLongConsumer Takes one input parameter of type Object and one input parameter of type long, with no return value.
Predicate Takes an input parameter and returns a Boolean result.
Supplier Returns a result with no arguments.
ToDoubleBiFunction Takes two input arguments and returns a double
ToDoubleFunction Takes an input parameter and returns a result of type double
ToIntBiFunction Takes two input arguments and returns an int.
ToIntFunction Takes an input parameter and returns a result of type int.
ToLongBiFunction Takes two input parameters and returns a result of type long.
ToLongFunction Takes an input parameter and returns a result of type long.
UnaryOperator Accepts an argument of type T and returns a value of type T.

(The table above is from the rookie tutorial.)

3. The Lambda syntax

The syntax of Lambda is mainly the following.

  1. (params) -> expression

  2. (params) -> {statements; }

The syntactic properties of Lambda.

  1. use->Split Lambda arguments and process statements.
  2. Type Optional, you can not specify the parameter type, the compiler can automatically determine.
  3. Parentheses are optional. If there is only one parameter, you do not need parentheses. Multiple parameters must be parentheses.
  4. Curly braces are optional. You can use curly braces for a single statement, and curly braces are required for multiple parameters.
  5. The return value is optional. If there is only one expression, the value can be returned automatically without a return statement. Return syntax is required in curly braces. 6. The external variable referenced in the Lambda must be of final type, the internally declared variable cannot be modified, and the internally declared variable name cannot be the same as the external variable name.

Just to give you a few concrete examples, params with only one parameter or no parameter can be omitted, like this.

// 1. No argument, no return value, output Hello
()->System.out.pritnln("hello");

// 2. No arguments, return Hello() - >"hello";

// 3. Takes two arguments (numbers) and returns the sum of the two numbers
(x, y) -> x + y  
  
// 4. Takes two numeric arguments and returns the sum of the two numbers
(int x, int y) -> x + y  
  
If both numeric parameters are greater than 10, return and; if both are less than 10, return difference
(int x,int y) ->{
  if( x > 10 && y > 10) {return x + y;
  }
  if( x < 10 && y < 10) {returnMath.abs(x-y); }};Copy the code

In the above cases, you already have an idea of the syntactic structure of Lambda.

4. Use Lambda

4.1 For functional interfaces

The Runnable interface is already a function interface that can be implicitly converted to Lambda expressions for use. See how Lambda expressions are used in Java 8 using the thread creation and run example below.

/** * Lambda use, using Runnable example *@throws InterruptedException
 */
@Test
public void createLambda(a) throws InterruptedException {
    // Before using Lambda
    Runnable runnable = new Runnable() {
        @Override
        public void run(a) {
            System.out.println("Thread creation before JDK8"); }};new Thread(runnable).start();
   // After using Lambda
   Runnable runnable1Jdk8 = () -> System.out.println("Thread creation after JDK8");
   new Thread(runnable1Jdk8).start();
   // A more compact approach
   new Thread(() -> System.out.println("Thread creation after JDK8")).start();
}
Copy the code

As you can see, Lambda in Java 8 encounters the function interface Runnable, automatically inferences the run method to run, not only eliminating the need to write the run method, but also making the code more compact.

The result is as follows.

The thread before JDK8 creates the thread after JDK8 creates the thread after JDK8Copy the code

The Runnable function interface has no arguments. If it has arguments, how to use it? We write a function interface and write a say method that takes two arguments.

/** * defines the function interface */
@FunctionalInterface
public interface FunctionInterfaceDemo {
    void say(String name, int age);
} 
Copy the code

Write a test class.

 /** * function interface, Lambda test */
 @Test
 public void functionLambdaTest(a) {
     FunctionInterfaceDemo demo = (name, age) -> System.out.println("My name is" + name + "This is my year." + age + "Old");
     demo.say("Jin yong".99);
 }
Copy the code

Output the result.

My name is Jin Yong and I am this year99Years old.Copy the code

4.2 For method references

Method references are a concept that has not been introduced before. Method references give us direct access to an instance or method of a class, rather than the way Lambda is written to simply execute a method: instance/class :: method. This not only makes the code more compact, but also increases the readability of the code.

Look at method references through an example.

@Getter
@Setter
@ToString
@AllArgsConstructor
static class User {
    private String name;
    private Integer age;
}
public static List<User> userList = new ArrayList<User>();
static {
    userList.add(new User("A".26));
    userList.add(new User("B".18));
    userList.add(new User("C".23));
    userList.add(new User("D".19));
}
/** * Test method references */
@Test
public void methodRef(a) {
    User[] userArr = new User[userList.size()];
    userList.toArray(userArr);
    // User::getAge calls the getAge method
    Arrays.sort(userArr, Comparator.comparing(User::getAge));
    for(User user : userArr) { System.out.println(user); }}Copy the code

Get the output.

Jdk8Lambda.User(name=B, age=18) Jdk8Lambda.User(name=D, age=19) Jdk8Lambda.User(name=C, age=23) Jdk8Lambda.User(name=A, age=26)

4.3 For traversal mode

Lambda introduced new traversal methods, and Java 8 added foreach methods for collections that accept functional interfaces for manipulation. Let’s look at the set traversal of Lambda.

/** * new traversal method */
@Test
public void foreachTest(a) {
    List<String> skills = Arrays.asList("java"."golang"."c++"."c"."python");
    // Before using Lambda
    for (String skill : skills) {
        System.out.print(skill+",");
    }
    System.out.println();
    // After using Lambda
    / / 1, a forEach + lambda
    skills.forEach((skill) -> System.out.print(skill+","));
    System.out.println();
    // forEach+ method reference
    skills.forEach(System.out::print);
}
Copy the code

Run to get the output.

java,golang,c++,c,python,
java,golang,c++,c,python,
javagolangc++cpython
Copy the code

4.4 For streaming operations

Thanks to the introduction of Lambda, streaming operations in Java 8 are made possible. Java 8 provides the Stream class for obtaining data streams, which focuses on various efficient and convenient operations on data sets, improving programming efficiency, and simultaneously supports serial and parallel convergent computing. Can make full use of multi-nuclear advantages.

Streaming operations are so powerful, how can Lambda be used in streaming operations? Let’s feel the convenience and efficiency of flow operation.

Streaming operations start here.

// Create a serial stream for the collection
stream()
// Create a parallel flow for the collection
parallelStream()
Copy the code

De-weight distinct and filter filter for streaming operations.

@Test
public void streamTest(a) {
    List<String> skills = Arrays.asList("java"."golang"."c++"."c"."python"."java");
    / / before Jdk8
    for (String skill : skills) {
        System.out.print(skill + ",");
    }
    System.out.println();
    // after Jdk8 - go through again
    skills.stream().distinct().forEach(skill -> System.out.print(skill + ","));
    System.out.println();
    // after Jdk8 - go through again
    skills.stream().distinct().forEach(System.out::print);
    System.out.println();
    // after Jdk8 - de-weight, filter out ptyhon againskills.stream().distinct().filter(skill -> skill ! ="python").forEach(skill -> System.out.print(skill + ","));
    System.out.println();
    // Jdk8 after the string
    String skillString = String.join(",", skills);
    System.out.println(skillString);
}
Copy the code

Run to get the result.

java,golang,c++,c,python,java,
java,golang,c++,c,python,
javagolangc++cpython
java,golang,c++,c,
java,golang,c++,c,python,java
Copy the code

Data transformation (also known as mapping) maps for streaming operations.

 /** * Data conversion */
 @Test
 public void mapTest(a) {
     List<Integer> numList = Arrays.asList(1.2.3.4.5);
     // Data conversion
     numList.stream().map(num -> num * num).forEach(num -> System.out.print(num + ","));

     System.out.println();

     // Data collection
     Set<Integer> numSet = numList.stream().map(num -> num * num).collect(Collectors.toSet());
     numSet.forEach(num -> System.out.print(num + ","));
 }
Copy the code

Run to get the result.

1,4,9,16,25,
16,1,4,9,25,
Copy the code

Mathematical calculation of flow operations.

/** * Math test */
@Test
public void mapMathTest(a) {
    List<Integer> list = Arrays.asList(1.2.3.4.5);
    IntSummaryStatistics stats = list.stream().mapToInt(x -> x).summaryStatistics();
    System.out.println("Minimum:" + stats.getMin());
    System.out.println("Maximum value:" + stats.getMax());
    System.out.println("Number:" + stats.getCount());
    System.out.println("And:" + stats.getSum());
    System.out.println("Average:" + stats.getAverage());
    // Another way of summing
    Integer integer = list.stream().reduce((sum, cost) -> sum + cost).get();
    System.out.println(integer);
}
Copy the code

Run to get the result.

Get output min: 1 Max: 5 Count: 5 and 15 average: 3.0 15Copy the code

5. Lambda summary

Lamdba combines function interfaces, method references, type derivation, and streaming operations to make code more compact and to develop more powerful programs that support parallel computation. Function programming also brings a new approach to Java programming. However, the disadvantages are also obvious. In practical use, you may find the mode difficult. Tests show that Lamdba’s traversal performance is not as good as for’s performance, and colleagues may not understand Lamdba because they have not studied it (this article is recommended).

The article code has been uploaded to github.com/niumoo/jdk-… .

After < >

Hello world:) I’m Aaron, a tech tool guy on the front line.

Everyone who likes and comments is talented, not only handsome and good-looking, but also nice to talk.

The article is constantly updated, you can search “program Ape Alang” on wechat or visit “program ape Alang blog” to read it for the first time.

I have prepared a series of knowledge points and must-see books.

This article Github.com/niumoo/Java… Welcome to Star!