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
相关推荐
fouryears_2341733 分钟前
Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
开发语言·flutter·客户端·dart
我好喜欢你~1 小时前
C#---StopWatch类
开发语言·c#
lifallen2 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研2 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
wyiyiyi3 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
mit6.8243 小时前
[1Prompt1Story] 滑动窗口机制 | 图像生成管线 | VAE变分自编码器 | UNet去噪神经网络
人工智能·python
没有bug.的程序员3 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋4 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
cui__OaO4 小时前
Linux软件编程--线程
linux·开发语言·线程·互斥锁·死锁·信号量·嵌入式学习
鱼鱼说测试4 小时前
Jenkins+Python自动化持续集成详细教程
开发语言·servlet·php