Lamda表达式
以极其简略的方式创建一个接口的实例,通常只适用于一个接口中只有一个方法的接口形式
具体形式:
1. () -> () //只有一个参数或一个表达式()可以直接省略: A a = s -> System.out.println(s);
2. () -> {}
使用Lambda时,要记住的就两点:
- Lambda返回的是接口的实例对象
- 有没有参数、参数有多少个、需不需要有返回值、返回值的类型是什么---->选择自己合适的函数式接口
第一个例子:
PriorityQueue<ListNode> heap = new PriorityQueue<>((ListNode a,ListNode b) -> (a.val - b.val)); // 实例化一个优先队列
(ListNode a,ListNode b) -> (a.val - b.val) 就是lamda表达式 实现的是Comparator接口
这个表达式在干什么?进入PriorityQueue源码观察其构造函数
...
public PriorityQueue(Comparator<? super E> comparator) {
this(DEFAULT_INITIAL_CAPACITY, comparator);
}
...
再看这个Comparator接口的源码
@FunctionalInterface //这个是java 8提供的可以使用lamda表达式来实现应用型接口的
public interface Comparator<T> {
...
}
第二个例子:
public class Test {
public static void main(String[] args) {
A a = ()->{
System.out.println("实现void m()");
}; //实例了一个普通接口
a.m();
}
}
interface A {
void m();
}
第三个例子:
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();
}
四种应用型接口
此部分转自:https://www.zhihu.com/question/37872003/answer/2546842195
1.供给型接口
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
使用:
Supplier<Integer> s = ()-> (int) (Math.random()*100+1);
Integer num = s.get();
2.消费型接口
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
使用:
Consumer<Integer> c = (s) -> {System.out.println("run!!"+s);};
c.accept(5);
3.断言型接口
@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);
}
使用:
Predicate<String> p = (str)-> str.contains("ok");
boolean result = p.test("iamok");
4.函数型接口
@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);
}
使用:
Function<int[], Integer> f = (arr)-> {
Arrays.sort(arr);
return arr[0];
};
int max = f.apply(new int[]{1,3,2});