Java 8 lambda表达式

时间:2020-12-25 22:11:18

使用lambda表达式

可以在函数式接口上使用Lambda表达式。所谓函数式接口,就是只定义一个抽象方法的接口。比如Comparator、Runnable,以及Callable。Java 8在java.util.function包中引入了几个新的函数式接口。

----------------------------------------------------------------------------------------------------------------------------

写法对比

实现Runnable接口

 Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("bee !!");
            }
        };

lambda表达式实现Runnable接口

Runnable bee = () -> System.out.println("bee !!");

 

实现Comparator接口

  Collections.sort(list, new Comparator<ScoreCount>() {
            public int compare(ScoreCount o1, ScoreCount o2) {
                if (null == o1.getAll_s()) {
                    return 1;
                }
                if (null == o2.getAll_s()) {
                    return -1;
                }
                return o2.getAll_s().compareTo(o1.getAll_s());
            }
        });
       

lambda表达式实现Comparator接口


        Collections.sort(list, (o1,o2) -> {
                if (null == o1.getAll_s()) {
                    return 1;
                }
                if (null == o2.getAll_s()) {
                    return -1;
                }
                return o2.getAll_s().compareTo(o1.getAll_s());
        });

更加细节的lambda表达式解析

https://blog.csdn.net/qmqm011/article/details/82427570