Lambda表达式-----来自小萌新的整理

Lambda表达式

作为JDK1.8的新特性,Lambda是一个匿名函数,可以把Lambda表达式理解成一段可以传递的代码(代码像数据一样传递)。

Lambda表达式的基础语法

Java8中引入了一个新的操作符“->”,该操作符称为箭头操作符lambda操作符
操作符左侧:Lambda表达式的参数列表
操作符右侧:Lambda表达式所需要执行的功能,即Lambda体

感觉就是简化代码,但是对于不懂的人来说可读性会比较差。

先来一个小案例


先定义一个People类,属性随便给了仨。
在这里插入图片描述然后在测试类中定义一个集合,里面存点数据

接下来比如说有个需求:查询出年龄大于15的人

//需求:查询出年龄大于15的人
    public List<People> getPeoperWithAge(List<People> list){
        List<People> peopleList=new ArrayList<>();
        for (People people : list) {
            if (people.getAge()>15){
                peopleList.add(people);
            }
        }
        return peopleList;
    }
 @Test
    public void test(){
        List<People> peoperWithAge = getPeoperWithAge(peopleList);
        for (People people : peoperWithAge) {
            System.out.println(people);
        }
    }

结果输出:
在这里插入图片描述

现在又来一个新的需求:查询出性别是男的人

//需求:查询出性别是男的人
    public  List<People> getPeopleWithSex(List<People> list){
        List<People> peopleList=new ArrayList<>();
        for (People people : list) {
            if (people.getSex()=='男'){
                peopleList.add(people);
            }
        }
        return peopleList;
    }
@Test
    public void test1(){
        List<People> peopleWithSex = getPeopleWithSex(peopleList);
        for (People people : peopleWithSex) {
            System.out.println(people);
        }
    }

输出结果:
在这里插入图片描述上面代码看起来是不是有点冗余,就是两个需求方法中的if判断的条件不一样,其它的代码都一模一样。所以就有了接下来的几种进阶版本。

改进版:策略设计模式
先定义一个接口:

public interface MyPredicate<T> {
    public boolean test(T t);
}

根据不同的需求定义对应的实现类

public class GetPeopleByAge implements MyPredicate<People> {
	//需求:查询出年龄大于15的人
    @Override
    public boolean test(People people) {

        return people.getAge()>15;
    }
}
public class GetPeopleBySex implements MyPredicate<People> {
   //查询出性别是男的人
    @Override
    public boolean test(People people) {
        return people.getSex()=='女';
    }
}

接下来定义一个方法来实现不同的需求

//改进版---策略设计模式
    public List<People> getPeopleWithCondition(List<People> list, MyPredicate<People> my){
        List<People> peopleList=new ArrayList<>();
        for (People people : list) {
            if (my.test(people)){
                peopleList.add(people);
            }
        }
        return peopleList;
    }

调用该方法去实现需求:

@Test
    public void test2(){
        List<People> peopleWithAge = getPeopleWithCondition(peopleList, new GetPeopleByAge());
        for (People people : peopleWithAge) {
            System.out.println(people);
        }
    }
    @Test
    public void test3(){
        List<People> peopleWithSex = getPeopleWithCondition(peopleList, new GetPeopleBySex());
        for (People people : peopleWithSex) {
            System.out.println(people);
        }
    }

这样其实你还能发现一些问题:每个需求还得写类去实现接口,麻烦!!

改进版:匿名内部类
我不用写具体的类去实现接口了,我直接去new接口,然后重写接口里面的方法(具体的需求我重写方法的时候去定义)。

@Test
    public void test4(){
        List<People> peopleWithAge = getPeopleWithCondition(peopleList, new MyPredicate<People>() {
            @Override
            public boolean test(People people) {
                return people.getAge() > 20;
            }
        });
        for (People people : peopleWithAge) {
            System.out.println(people);
        }
    }

其实不难看出,上面的代码,其实真正可读性的代码比较少。于是它就出来简化了。

改进版:Lambda表达式
先看代码,等会再说格式…

@Test
    public void test5(){
        List<People> peopleWithAge = getPeopleWithCondition(peopleList, (p) -> p.getAge() > 15);
       peopleWithAge.forEach(System.out::println);
    }

其实还有一个改进版:stream API
代码如下,想了解的可以去了解一下

//进阶版--stream API
    @Test
    public void test6(){
        peopleList.stream()
                .filter((p) -> p.getAge() > 15)
                .forEach(System.out::println);
    }

Lambda表达式的使用前提

表达式需要函数式接口(SAM(Single Abstract Method)类型的接口)的支持:接口中只有一个抽象方法的接口,称为函数式接口。
可以使用@FunctionalInterface注解修饰一下,目的是检查是否是函数式接口。(可加可不加)
原则上说这个接口中只能有一个方法被实现,但是也有例外:
1.static和default修饰的方法不算
2.Object中覆盖的equals和toString等等方法不算

Lambda表达式的几种语法格式

可以先参考这个模板
(参数列表)->{Lambda体}

一、接口中方法无参无返回值

/**
     * 1.语法格式一:无参数无返回值,方法体中一条语句则大括号可以不写
     *
     */
    @Test
    public void test8(){
    	//这个匿名内部类,与下面lambda表达式做比较可能会更好理解,下面都不写匿名内部类了
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                System.out.println("object");
            }
        };
        runnable.run();
        System.out.println("---------------分割线---------------");
        //小括号里面写的是实现方法的形参列表,没有参数的话就写一个小括号,方法体中如果只有一条语句则{}可以省略不写
        Runnable  r=()-> System.out.println("new object");
        r.run();

    }

二、一个参数无返回值

 /**
     * 2.语法格式二:有一个参数并且无返回值,因为只有一个参数(类型可以不写会自动识别),所以参数的小括号可以省略
     * (这个接口不清楚的可以点进去看看,里面就一个抽象方法 一个参数无返回值)
     */

    @Test
    public void test9(){
        Consumer<String> consumer=a-> System.out.println(a);
        consumer.accept("new object");
    }

三、多个参数,有返回值,方法体中多条语句

/**
     * 3.语法格式三:有两个及以上参数(参数类型一样时可以省略类型不写,不能部分写部分不写,参数类型不一样都得写),有返回值,并且方法体中有多条语句
     *  类型之所以可不写是因为jvm编译器会通过上下文推断出类型
     */
    @Test
    public void test10(){
        Comparator<Integer> comparator=(a, b)->{
            System.out.println("new object");
            return Integer.compare(a,b);
        };
        System.out.println(comparator.compare(4,5));

    }

四、有两个及以上参数,有返回值,方法体中只有一条return语句

@Test
    public void test11(){
        Comparator<Integer> comparator=(a, b)->Integer.compare(a,b);

    }

总结一下

借用之前看视频时候老师的一副对联:
上联:左右遇一括号省
下联:左侧推断类型省
横批:能省则省

稍微解释一下:左边一个参数可省小括号,右边一条语句时省大括号/如果一条语句是return,return也可以省
左边给了类型的话,右边参数类型一致时可以不写参数类型

萌新上路------欢迎大佬指正批评。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值