01 Lambda 表达式

1 Lambda 表示式的形式

根据方法参数个数的不同、方法体内语句数量的不同,Lambda 表达式的形式呈现多种多样。

package com.hcong.functional;

/**
 * @Classname LambdaExpressions
 * @Date 2023/4/7 16:59
 * @Created by HCong
 */
interface Description {
    String brief();
}

interface Body {
    String detailed(String head);
}

interface Multi {
    String twoArg(String head, Double d);
}

public class LambdaExpressions {
    static Description desc = () -> "Short info";  // [1]

    static Body bod1 = h -> h + " No parens!";     // [2]

    static Body bod2 = h -> h + " More details";   // [3]

    static Multi mult = (h, n) -> h + n;           // [4]

    static Description moreLines = () -> {         // [5]
        System.out.println("moreLines()");
        return "from moreLines()";
    };

    public static void main(String[] args) {
        System.out.println(desc.brief());
        System.out.println(bod1.detailed("Oh!"));
        System.out.println(bod2.detailed("Hi!"));
        System.out.println(mult.twoArg("Pi! ", 3.14159));
        System.out.println(moreLines.brief());
    }
}

Short info
Oh! No parens!
Hi! More details
Pi! 3.14159
moreLines()
from moreLines()

2 Lambda 表达式与递归

若需要将递归方法编写成 Lambda 表达式的形式,那么递归方法必须是实例变量或静态变量。

package com.hcong.functional;

/**
 * @Classname RecursiveFactorial
 * @Date 2023/4/7 17:07
 * @Created by HCong
 */
interface IntCall {
    int call(int arg);
}

public class RecursiveFactorial {
    static IntCall fact;

    public static void main(String[] args) {
        fact = n -> n == 0 ? 1 : n * fact.call(n - 1);
        for (int i = 0; i <= 10; i++) System.out.println(fact.call(i));
    }
}

1
1
2
6
24
120
720
5040
40320
362880
3628800
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是聪聪黄吖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值