Java 8 lambda表达式

使用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

posted @ 2019-07-18 14:01  爪哇搬砖  阅读(141)  评论(0编辑  收藏  举报