lambda expression in jdk8

Keywords: Java Lambda

lambda expressions

Optimization of lambda

The following abbreviations can be used in JDK8

new Thread(() -> System.out.println("Multithread task execution!")).start(); // Startup thread
Arrays.sort(array,(a,b)->a.getAge()-b.getAge())    //sort

Format of Lambda

Standard format:
(parameter type parameter name) - > {code statement}

Ellipsis format:
(a, b) - > {code}

Prerequisites of Lambda

  • Lambda must have an interface, and requires that there is only one abstract method in the interface. For example, Runnable and Comparator // Functional Interfaces
  • Lambda must have an interface as a method parameter.

Functional interface

Definition

Functional Interface: An interface with and only one abstract method.

format

Modifier interface name{
     public abstract return value type method name (optional parameter information); // other non-abstract method content 
}

Custom Functional Interface

@FunctionalInterface    //Writable but not Writable, similar to @Override
public interface MyFunctionalInterface { void myMethod(); } //Define an interface

public class Demo07FunctionalInterface { // Use custom functional interfaces as method parameters 
    private static void doSomething(MyFunctionalInterface inter) {         
        inter.myMethod(); // Call a custom functional interface method 
    }
    
    public static void main(String[] args) { // Call methods that use functional interfaces 
        doSomething(() -> System.out.println("Lambda Execute!")); 
    } 
}

Common Functional Interfaces

Consumer interface

Consumer < T > interface is to consume a data, abstract method accept, basic use as follows:
//Give you a string. Please consume it in capitals. 
import java.util.function.Consumer; 
public class Demo08Consumer {
     public static void main(String[] args) {
          String str = "Hello World"; 
          //1.lambda expression standard format 
          fun(str,(String s)->{ System.out.println(s.toUpperCase());});             
          //2. Simplified Format of Lambda Expressions
          fun(str,s-> System.out.println(s.toUpperCase())); 
     }
          /* Define method, using Consumer interface as parameter fun method: 
          Consumption of a String-type variable */ 
     public static void fun(String s,Consumer<String> con) {
        con.accept(s); 
     } 
}

Predicate interface

Stream flow

Posted by artfuldrone on Fri, 04 Oct 2019 17:02:49 -0700