2026-01-12 20:08:37
Lambda表达式是Java 8引入的一种简洁的函数式编程特性,允许将代码作为参数传递,核心优势在于简化函数式接口的实现。以下从语法、分类、函数式接口配合、方法引用、变量作用域及使用注意事项展开说明:
1. Lambda表达式语法可选类型声明:参数类型可省略(编译器自动推断)。
可选圆括号:单参数可省略(),无参数或多个参数需保留。
可选大括号:单语句可省略{},多语句需保留。
可选返回关键字:单表达式返回值时自动返回,多语句需显式return。
根据参数和返回值的不同,分为四类:
(1)无参无返回值new Thread(() -> System.out.println("Hello")).start();(2)有参无返回值list.forEach(t -> System.out.print(t + "t"));// 或使用方法引用list.forEach(System.out::println);(3)无参有返回值Stream<Integer> stream = Stream.generate(() -> new Random().nextInt(100));stream.forEach(t -> System.out.println(t));(4)有参有返回值TreeSet<Student> set = new TreeSet<>((s1, s2) -> collator.compare(s1.getName(), s2.getName()));3. 函数式接口配合Consumer:消费型,void accept(T t)。
Supplier:供给型,T get()。
Predicate:断定型,boolean test(T t)。
Function<T, R>:函数型,R apply(T t)。
示例:
@FunctionalInterfaceinterface IMyInterface { void study();}public class Test { public static void main(String[] args) { IMyInterface i = () -> System.out.println("I like study"); i.study(); }}4. 方法引用当Lambda仅调用已有方法时,可用方法引用进一步简化:
// Lambda表达式Supplier<Student> s1 = () -> new Student();// 方法引用Supplier<Student> s2 = Student::new;5. Lambda变量作用域理解函数式接口与Lambda的绑定关系。
掌握不同分类的语法及适用场景。
注意变量作用域和命名冲突规则。
通过合理使用Lambda表达式,可以显著减少冗余代码,尤其在集合操作、多线程和Stream API中效果显著。