Lamda expressions in Java

Lamda expression

Create an instance of an interface in an extremely simple way, usually only suitable for interface forms with only one method in an interface

Specific forms:

1. () -> ()  //只有一个参数或一个表达式()可以直接省略: A a = s -> System.out.println(s);
2. () -> {}

When using Lambda, there are two things to remember:

  1. Lambda returns the instance object of the interface
  2. Are there any parameters, how many parameters are there, whether there is a return value, and what is the type of the return value----> Choose your appropriate functional interface

First example:

PriorityQueue<ListNode> heap = new PriorityQueue<>((ListNode a,ListNode b) -> (a.val - b.val)); // 实例化一个优先队列
(ListNode a,ListNode b) -> (a.val - b.val) 就是lamda表达式  实现的是Comparator接口

What is this expression doing? Enter the PriorityQueue source code to observe its constructor

...
public PriorityQueue(Comparator<? super E> comparator) {
        this(DEFAULT_INITIAL_CAPACITY, comparator);
    }
...

Let’s look at the source code of this Comparator interface again

@FunctionalInterface    //这个是java 8提供的可以使用lamda表达式来实现应用型接口的
public interface Comparator<T> {
...
}

Second example:

public class Test {
    public static void main(String[] args) {
        A a = ()->{
          System.out.println("实现void m()");  
        };    									//实例了一个普通接口
 
        a.m();
    }
}

interface A {
    void m();
}

Third example:

new Thread(() -> System.out.println("run!!"));  //实例化Runnable接口
@FunctionalInterface 
public interface Runnable {
    /**
     * When an object implementing interface {@code Runnable} is used
     * to create a thread, starting the thread causes the object's
     * {@code run} method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method {@code run} is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

Four application interfaces

This part is reproduced from: https://www.zhihu.com/question/37872003/answer/2546842195

1. Supply interface

@FunctionalInterface
public interface Supplier<T> {
    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

use:

Supplier<Integer> s = ()-> (int) (Math.random()*100+1);
Integer num = s.get();

2.Consumption interface

@FunctionalInterface
public interface Consumer<T> {
    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
 
}

use:

Consumer<Integer> c = (s) -> {System.out.println("run!!"+s);};
c.accept(5);

3. Assertive interface

@FunctionalInterface
public interface Predicate<T> {
    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);
 
 }

use:

Predicate<String> p = (str)-> str.contains("ok");
boolean result = p.test("iamok");

4. Functional interface

@FunctionalInterface
public interface Function<T, R> {
    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
 
}

use:

Function<int[], Integer> f = (arr)-> {
    Arrays.sort(arr);
    return arr[0];
};

int max = f.apply(new int[]{1,3,2});

Guess you like

Origin blog.csdn.net/qq_40893490/article/details/125601481