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
相关推荐
阿贵---5 分钟前
使用XGBoost赢得Kaggle比赛
jvm·数据库·python
88号技师6 分钟前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t198751287 分钟前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
无敌昊哥战神9 分钟前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
m0_7269659843 分钟前
面面面,面面(1)
java·开发语言
2401_831920741 小时前
分布式系统安全通信
开发语言·c++·算法
~无忧花开~1 小时前
React状态管理完全指南
开发语言·前端·javascript·react.js·前端框架
李昊哲小课2 小时前
第1章-PySide6 基础认知与环境配置
python·pyqt·pyside
阿贵---2 小时前
C++中的RAII技术深入
开发语言·c++·算法
Traced back2 小时前
怎么用 Modbus 让两个设备互相通信**,包含硬件接线、协议原理、读写步骤,以及 C# 实操示例。
开发语言·c#