lambda表达式常用01

1、优化线程代码

以前我们使用线程可能是这么使用的:

new Thread(new Runnable(){
    @Override
    public void run() {
        System.out.println("thread run");
    }
}).start();

使用lambda: 

new Thread(()->{
     System.out.println("thread run");
}).start();

再次进行优化写法:

new Thread( ()->System.out.println("thread run")).start();

  

2.Arrays.sort排序优化

在代码中,我们会使用Arrays.sort对数据进行排序,Arrays.sort是可以对数组、列表集合进行排序的,很多时候会使用的到。

使用lambda:

Arrays.sort(playerScore,(Integer o1,Integer o2)->o1.compareTo(o2) );

类型Integer也可以去掉优化成: 

Arrays.sort(playerScore,(o1,o2)->o1.compareTo(o2) );

再次优化:

Arrays.sort(playerScore,Comparator.comparing(Integer::intValue));

注:其中Integer::intValue(方法引用使用一对冒号 ::),就是Integer类中的方法intValue:

从高到底:

Arrays.sort(playerScore,Comparator.comparing(Integer::intValue).reversed());

对于compareTo从高到底就只需要调整下o1和o2的位置了: 

Arrays.sort(playerScore,(o1,o2)->o2.compareTo(o1));

  

3.List遍历

languages.forEach(language-> System.out.print(language+","));

  

 4.Map遍历

map.forEach((key,value)->System.out.println("key:"+key+",value:"+value) );

对于对于Map如果没获取到key的话,我们会有一个默认值的显示,比如显示为“-”或者“无”:

System.out.println("birthday:"+map.getOrDefault("birthday","-"));

 

posted @ 2022-06-01 18:04  道行太浅  阅读(24)  评论(0编辑  收藏  举报