Lambda表达式

lambda表达式

1.语法

  • (参数列表) -> 表达式
  • (参数列表) -> {方法体}

2.函数式接口

Lambda表达式只能用于函数式接口,即那些只包含一个抽象方法的接口。

函数式接口必须满足以下条件

  • 只有一个抽象方法
  • 可以包含多个默认方法和静态方法(这些不会影响其函数式的特性)
  • 使用@FunctionalInterface注解来标注,虽然不是强制性的,但它可以确保编译器检查该接口是否符合函数式接口的定义。
java 复制代码
@FunctionalInterface
public interface MyFunctionalInterface {
    void myMethod();  // 抽象方法
}
MyFunctionalInterface myFunc = () -> System.out.println("Hello from Lambda!");
myFunc.myMethod();  // 输出:Hello from Lambda!

3.预定义的函数式接口

  • Supplier<T>
    • 无参数,返回类型为T的值。
    • 常用于延迟计算或提供对象实例。
java 复制代码
@FunctionalInterface
public interface Supplier<T> {
    T get();
}
Supplier<String> supplier = () -> "Hello, Supplier!";
System.out.println(supplier.get());
  • Consumer<T>
    • 接受一个参数,但没有返回值。
    • 常用于对传入对象进行操作(例如打印、修改等)。
java 复制代码
@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}
Consumer<String> consumer = s -> System.out.println(s);
consumer.accept("Hello, Consumer!");  // 输出:Hello, Consumer!
  • Function<T, R>
    • 接收一个类型为T的参数,返回一个类型为R的值。
    • 常用于对象转换或计算。
java 复制代码
@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}
Function<Integer, String> function = num -> "Number: " + num;
System.out.println(function.apply(5));  // 输出:Number: 5
  • Predicate<T>
    • 接受一个参数,返回一个boolean值。
    • 常用于条件判断和过滤。
java 复制代码
@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}
Predicate<Integer> isEven = num -> num % 2 == 0;
System.out.println(isEven.test(4));  
  • BiFunction<T, U, R>
    • 接收两个参数,返回一个结果。
    • 适合处理两个参数之间的关系。
java 复制代码
@FunctionalInterface
public interface BiFunction<T, U, R> {
    R apply(T t, U u);
}
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
System.out.println(add.apply(3, 5));  // 输出:8
  • Runnable
    • 无参数也无返回值的接口,常用于线程执行。
java 复制代码
@FunctionalInterface
public interface Runnable {
    public abstract void run();
}
Runnable runnable = () -> System.out.println("Running in thread");
runnable.run();  // 输出:Running in thread
相关推荐
code2cat2 小时前
Java进阶篇之AtomicReferenceFieldUpdater:用不可变快照替换整份状态
java·开发语言·cas
Nathan__272 小时前
PHP面试题——情景应用
开发语言·php
geats人山人海2 小时前
现代c++2.4 虚继承
java·开发语言·c++
我命由我123453 小时前
Android 广播 - 组件通信
android·java·开发语言·android studio·android jetpack·android-studio·android runtime
前端 贾公子3 小时前
LangGraph == 图的状态(State)管理 (中)
开发语言·数据库·python
李福春3 小时前
斗破Google ADK Java苍穹-第2境斗者-凝旋筑基-Java环境
java·开发语言·gemini·llmagent·深圳同盟·腾讯云架构师技术同盟·adk java
the局外人4 小时前
FastAPI中jwt的基本使用与实践
后端·python·fastapi
老王爱玩车4 小时前
预处理详解
c语言·开发语言·学习
mklpo1474 小时前
为不支持sse4.2命令集的老旧设备制作Win11 26H2系统镜像,2026-10-11。
运维·windows·python
GoldenSpider.AI4 小时前
用 AI 改流程之前先做「四桶」体检:9 次返工里 8 次靠规则就能消掉(附 Python 发布前校验器)
人工智能·python·自动化·ai智能体