在 Java 中,Lambda 表达式只能用于“函数式接口”(Functional Interface),也就是有且仅有一个抽象方法的接口。
从“类型”角度来看,Java Lambda 表达式支持的“类型”可以分为以下几类:
Lambda 本质上是对函数式接口实例的简化写法,因此支持以下类型:
Runnable r = () -> System.out.println("Hello");
对应接口:
@FunctionalInterface
interface Runnable {
void run();
}
Consumer<String> c = s -> System.out.println(s);
对应接口:
@FunctionalInterface
interface Consumer<T> {
void accept(T t);
}
Function<Integer, Integer> f = x -> x * 2;
对应接口:
@FunctionalInterface
interface Function<T, R> {
R apply(T t);
}
Supplier<String> s = () -> "Hello";
对应接口:
@FunctionalInterface
interface Supplier<T> {
T get();
}
Predicate<Integer> p = x -> x > 0;
对应接口:
@FunctionalInterface
interface Predicate<T> {
boolean test(T t);
}
@FunctionalInterface
interface MyInterface {
int calculate(int a, int b);
}
MyInterface m = (a, b) -> a + b;
Lambda 还支持以下“类型”的简化写法:
Function<Integer, String> f = String::valueOf;
Consumer<String> c = System.out::println;
Supplier<List<String>> s = ArrayList::new;
❌ Lambda 不能用于:
Java 的 Lambda 表达式只支持“函数式接口类型”,包括 JDK 内置的
Runnable、Function、Consumer、Predicate、Supplier以及自定义函数式接口。
如果你愿意,我也可以帮你整理一份 「Java 常见函数式接口速查表」 或 「Lambda 与匿名内部类的区别」。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。