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
相关推荐
Allen说改装6 分钟前
2025 APAxpo佛山改装展的展出规模达到了多少平方米?
人工智能·python
@atweiwei19 分钟前
Langchainrust:中LLM-as-a-Judge,用 Rust 实现一套 LLM 评估系统
开发语言·后端·ai·rust·llm·rag
风华圆舞22 分钟前
鸿蒙HarmonyOS 多模态输入实战 —— 图片与文档输入智谱/DeepSeek
开发语言·人工智能·华为·php·harmonyos·arkts·arkui
Ljwuhe35 分钟前
C++——模板进阶
开发语言·c++
aqi0039 分钟前
15天学会AI应用开发(十四)搭建LangChain的开发环境
人工智能·python·大模型·ai编程·ai应用
中国搜索直付通1 小时前
避开直付通选型暗礁:二级商户的合规生存与背景甄别
java·大数据·开发语言·人工智能·游戏
想会飞的蒲公英1 小时前
词袋模型与 CountVectorizer:文本也可以做特征表
人工智能·python·机器学习
LadenKiller1 小时前
近期量化工具推荐,问题位置比功能清单更重要
人工智能·python
Hesionberger1 小时前
LeetCode406:重建身高队列精髓解析
开发语言·数据结构·python·算法·leetcode