0
点赞
收藏
分享

微信扫一扫

Lambda的笔记

技术只适用于干活 2022-03-12 阅读 39

Lambda的笔记

什么是Lambda?

1.Lambda是一种函数式的编程思想的概述,
在数学中,函数就是有输入量、输出量的一套计算方案,也就是“拿数据做操作”
面向对象思想强调“必须通过对象的形式来做事情”
函数式思想则尽量忽略面向对象的复杂语法:“强调做什么,而不是以什么形式去做”

而我们要学习的Lambda表达式就是函数式思想的体现

Lambda的基本要求和格式?

1.格式:
	(形式参数) -> {代码块}
形式参数:如果有多个参数,参数之间用逗号隔开;如果没有参数,留空即可
->:由英文中画线和大于符号组成,固定写法。代表指向动作
代码块:是我们具体要做的事情,也就是以前我们写的方法体内容
2.组成Lambda表达式的三要素:
	形式参数,箭头,代码块

Lambda的demo样例?

1.无参无返回值
在这里插入图片描述

public class EatableDemo {
    public static void main(String[] args) {
        hader(new Show() {
            @Override
            public void bb() {
                System.out.println("我是匿名内部类");
            }
        });
        hader(() -> {
            System.out.println("我是lamdba表达式");
        });
    }

    public static void hader(Show show) {
        show.bb();
    }
}

interface Show {
    void bb();
}

2.有参无返回值
在这里插入图片描述

/**
 * 有参无返回值
 */
public class test2 {
    public static void main(String[] args) {
        useFlyable(new Flyable() {
            @Override
            public void fly(String s) {
                System.out.println(s);
                System.out.println("我要去西藏");
            }
        });
        System.out.println("--------");
        useFlyable((String str)->{
            System.out.println(str);
        });

    }
    private static void useFlyable(Flyable f) {
        f.fly("风和日丽,晴空万里");
    }
}
interface Flyable {
    void fly(String s);
}

3.有参又返回值
在这里插入图片描述

/**
 * 有参有返回值
 */
public class test3 {
    public static void main(String[] args) {
        useAddable((int x,int y)->{
            return x+y;
        });

    }
    private static void useAddable(Addable a) {

        int sum = a.add(10, 20);
        System.out.println(sum);
    }

}
interface Addable {
    int add(int x,int y);
}
举报

相关推荐

0 条评论