lambda 表达式 介绍

  1. 基本语法形式(只有一个参数时)
    • Lambda 表达式主要用于替代匿名内部类,特别是在使用函数式接口(只有一个抽象方法的接口)的时候。当接口的抽象方法只有一个参数时,基本形式如下:
    • 语法:(parameter) -> expression
    • 例如,有一个函数式接口MyFunction,它有一个抽象方法apply,接受一个整数参数并返回该整数加 1 后的结果。
    • 首先定义函数式接口:
     
    @FunctionalInterface
    public interface MyFunction {
        int apply(int x);
    }
    
     
    • 然后使用 Lambda 表达式实现这个接口:
     
    MyFunction addOne = (x) -> x + 1;
    System.out.println(addOne.apply(5));//输出6
    
  2. 多个参数的情况
    • 语法:(parameter1, parameter2,...) -> expression
    • 例如,有一个函数式接口Calculator,它有一个抽象方法calculate,接受两个整数参数并返回它们的和。
    • 定义函数式接口:
     

    @FunctionalInterface
    public interface Calculator {
        int calculate(int a, int b);
    }
    
     
    • 使用 Lambda 表达式实现接口:
     

    Calculator adder = (a, b) -> a + b;
    System.out.println(adder.calculate(3, 4));//输出7
    
  3. 带有语句块的 Lambda 表达式
    • 当 Lambda 表达式中的逻辑不能用一个简单的表达式表示,而需要多条语句时,可以使用语句块。
    • 语法:(parameters) -> { statements; }
    • 例如,有一个函数式接口StringProcessor,它的抽象方法process接受一个字符串参数,将字符串转换为大写并在末尾添加一个感叹号。
    • 定义函数式接口:
    @FunctionalInterface
    public interface StringProcessor {
        String process(String input);
    }
    
     
    • 使用 Lambda 表达式实现接口:
     

    StringProcessor upperAndExclaim = (input) -> {
        String upperCase = input.toUpperCase();
        return upperCase + "!";
    };
    System.out.println(upperAndExclaim.process("hello"));//输出HELLO!
    
  4. 方法引用(一种特殊的 Lambda 表达式写法)
    • 方法引用是 Lambda 表达式的一种简洁写法,用于直接引用已经存在的方法。
    • 例如,有一个System.out.println方法,它接受一个对象并打印它。如果有一个函数式接口Printer,它的抽象方法print接受一个字符串并打印它。
    • 定义函数式接口:
     

    @FunctionalInterface
    public interface Printer {
        void print(String s);
    }
    
     
    • 可以使用方法引用System.out::println来实现这个接口:
     

    Printer printer = System.out::println;
    printer.print("This is a method reference.");
    
     
    • 这里System.out::println等价于(s) -> System.out.println(s)
    • 还有其他类型的方法引用,如引用某个类的静态方法(ClassName::staticMethodName)、引用某个对象的实例方法(objectReference::instanceMethodName)和引用某个类型的任意对象的实例方法(ClassName::instanceMethodName)。例如,对于一个String类的length方法,可以使用String::length作为方法引用来获取字符串长度的函数式接口实现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值