温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java Lambda表达式支持哪些类型

发布时间:2026-10-02 18:03:16 来源:亿速云 阅读:83 作者:小樊 栏目:编程语言

在 Java 中,Lambda 表达式只能用于“函数式接口”(Functional Interface),也就是有且仅有一个抽象方法的接口。
从“类型”角度来看,Java Lambda 表达式支持的“类型”可以分为以下几类:


一、按【函数式接口类型】分类(最常见)

Lambda 本质上是对函数式接口实例的简化写法,因此支持以下类型:

1️⃣ 无参数、无返回值

Runnable r = () -> System.out.println("Hello");

对应接口:

@FunctionalInterface
interface Runnable {
    void run();
}

2️⃣ 有参数、无返回值

Consumer<String> c = s -> System.out.println(s);

对应接口:

@FunctionalInterface
interface Consumer<T> {
    void accept(T t);
}

3️⃣ 有参数、有返回值

Function<Integer, Integer> f = x -> x * 2;

对应接口:

@FunctionalInterface
interface Function<T, R> {
    R apply(T t);
}

4️⃣ 无参数、有返回值

Supplier<String> s = () -> "Hello";

对应接口:

@FunctionalInterface
interface Supplier<T> {
    T get();
}

5️⃣ 判断型(返回 boolean)

Predicate<Integer> p = x -> x > 0;

对应接口:

@FunctionalInterface
interface Predicate<T> {
    boolean test(T t);
}

6️⃣ 自定义函数式接口

@FunctionalInterface
interface MyInterface {
    int calculate(int a, int b);
}

MyInterface m = (a, b) -> a + b;

二、按【方法引用 & 构造器引用类型】分类(Lambda 的简化形式)

Lambda 还支持以下“类型”的简化写法:

1️⃣ 静态方法引用

Function<Integer, String> f = String::valueOf;

2️⃣ 实例方法引用

Consumer<String> c = System.out::println;

3️⃣ 构造方法引用

Supplier<List<String>> s = ArrayList::new;

三、不支持的“类型”

❌ Lambda 不能用于:

  • 普通类
  • 抽象类(即使只有一个抽象方法)
  • 有多个抽象方法的接口
  • 非接口类型(如基本类型、数组直接当类型)

四、总结一句话

Java 的 Lambda 表达式只支持“函数式接口类型”,包括 JDK 内置的 Runnable、Function、Consumer、Predicate、Supplier 以及自定义函数式接口。

如果你愿意,我也可以帮你整理一份 「Java 常见函数式接口速查表」 或 「Lambda 与匿名内部类的区别」。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手