lambda表达式的简单应用

本文通过三个实例:使用Lambda表达式替代匿名内部类、遍历并过滤List集合、遍历并过滤Map集合,深入浅出地介绍了Java 8中Lambda表达式和Stream API的高效应用。通过对比传统写法,展示了Lambda表达式的简洁性和Stream API的强大功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.匿名内部类

@Test
public void test1(){
    System.out.println(666);
    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("aaa");
        }
    }).start();
    //替换方案
    new Thread(()-> System.out.println("aaa")).start();
}

2.遍历list

@Test
public void test2(){
    List<String> list = Arrays.asList("aaa","bbb","ccc");
    list.forEach(str-> System.out.println(str));
    //过滤
    list.stream().filter(str->"aaa".equals(str)).forEach(str->System.out.println(str));
    List<String> aaa = list.stream().filter(str -> "aaa".equals(str)).collect(Collectors.toList());
    //计算
    int num = (int)(list.stream().filter(str -> "aaa".equals(str)).count());
}

3.遍历Map

@Test
public void test3(){
    Map<String,String> map = new HashMap<>();
    map.put("A","Z");
    map.put("B","Z");
    map.put("C","C");
    map.put("D","V");
    map.forEach((key,value)-> System.out.println(key+value));
   //过滤
    Map<String, String> resultMap = map.entrySet().stream().filter(c -> "Z".equals(c.getValue())).collect(Collectors.toMap(c -> c.getKey(), c -> c.getValue()));
    resultMap.forEach((key,value)-> System.out.println(key+value));
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值