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
相关推荐
Eiceblue38 分钟前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
m0_555762901 小时前
Matlab 频谱分析 (Spectral Analysis)
开发语言·matlab
浪裡遊2 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
烛阴3 小时前
简单入门Python装饰器
前端·python
lzb_kkk3 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
好开心啊没烦恼3 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
面朝大海,春不暖,花不开3 小时前
使用 Python 实现 ETL 流程:从文本文件提取到数据处理的全面指南
python·etl·原型模式
简佐义的博客4 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang
程序员爱钓鱼4 小时前
【无标题】Go语言中的反射机制 — 元编程技巧与注意事项
开发语言·qt