什么是Lambda表达式?
JAVA8新特性,是一种匿名函数。它能够使代码变得简洁、紧凑,Lambda表达式实质上是个语法糖。
使用Lambda的前提
必须有一个函数式接口 有且只有一个抽象方法的接口 @FunctionnalInterface注解(可选)
常见的函数式接口
Runnable
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
Callable
@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
Supplier
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
Consumer
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
Comparator
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
}
Predicate
@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);
}
Function
@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);
}
Lambda表达式的语法格式
基本语法
具体案例
1.可选的大括号{}
函数体只包含一个语句,不需要大括号
// 1.函数体只有一个语句,省略大括号
(String msg) -> System.out.println("hello"+ msg);
2.可选的参数圆括号()
只有一个参数,省略圆括号,同时省略类型
// 2.只有一个参数,省略圆括号,同时省略类型
msg -> System.out.println("hello “ + msg);
3.可选的返回关键字return
函数体只有一个表达式,且运算结果匹配返回类型
// 3.函数体只有一个表达式,省略return
(int a, int b) -> a + b
4.可选的类型声明
不需要参数类型,编译器可以根据参数值进行推断
/ 4. 省略参数类型,编译器可以进行推断
(a, b) -> a + b
Lambda的底层实现?
它的本质是函数式接口的匿名子类的匿名对象。Lambda底层用匿名内部类实现。通过反编译可以看出
java -jar cfr-0.145.jar LambdaTest.class --decodelambdas false
源代码:
public class LambdaTest {
public static void main(String[] args) {
List<String> strList = Arrays.asList("xiao", "wang");
// 通过lambda表达式实现元素遍历
strList.forEach(s -> {
System.out.println(s);
});
}
}
cfr-0.145.jar包:
链接:https://pan.baidu.com/s/1HWoK8_Fy-YTRiXk8UitYRQ
提取码:1234
--来自百度网盘超级会员V5的分享