The use of Lambda

case

  • Create threads using anonymous functions
New Thread(new Runnable() {@Override public void run() {System.out.println(); } }).start(); }
  • Using lambda makes it easy to create threads
New Thread(() -> {System.out.println(" create threads using lambda "); }).start();

FunctionalInterface -> represents an interface with only one abstract method in the interface and is identified with the annotation @FunctionalInterface

Four function interface understanding

1.Consumer<T>

Receive a type with no return type

Use case

    public static void main(String[] args) {

        testConsumer("haha",str -> {
            System.out.println(str);
        });

        System.out.println("-----------------");
        
        testConsumer("haha",str -> System.out.println(str + str));
    }

    public static void testConsumer(String str,Consumer<String> consumer) {
        consumer.accept(str);
    }

Function<T,R>

T as the parameter type and R as the return type

Use case

Public static void main(String[] args) {/** return String length */ int length = testFunction(" testFunction ", str-> str.length()); System.out.println(length); } public static Integer testFunction(String str,Function<String,Integer> function) { return function.apply(str); }

Supplier<T>

T as the return type

Use case

Public static void main(String[] args) {/** Get a random value */ Double Adouble = testSupplier(() -> Math.random())); System.out.println(aDouble); } public static Double testSupplier(Supplier<Double> supplier) { return supplier.get(); }

Predicate<T>

T returns a Boolean value as an argument

Use case

Public static void main(String[] args) {Boolean isContain = testPredicate("String", str->) str.contains("s")); } public static boolean testPredicate(String str,Predicate<String> predicate) { return predicate.test(str); }

In lambda we can omit {} if there is only one line of code and we can omit return if we need to return value


Only one parameter can be omitted ()