V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
rqxiao
V2EX  ›  程序员

Variable used in lambda expression should be final or effectively final 的问题有什么好的写法 像这种吗

  •  
  •   rqxiao · 2019-10-09 17:42:05 +08:00 · 2482 次点击
    这是一个创建于 1632 天前的主题,其中的信息可能已经有所发展或是发生改变。

        List<Map<String, Object>> maps = baseMapper.selectMaps(queryWrapper);
        BigDecimal totalRecharge=new BigDecimal(0);
        maps.stream().findFirst().ifPresent(
                map->{
                     totalRecharge = (BigDecimal) map.get("totalRecharge");
                }
    
        );
        
        
        List<Map<String, Object>> maps = baseMapper.selectMaps(queryWrapper);
        final BigDecimal[] totalRecharge = {new BigDecimal(0)};
        maps.stream().findFirst().ifPresent(
                map->{
                     totalRecharge[0] = (BigDecimal) map.get("totalRecharge");
                }
    
        );
    
    4 条回复    2019-10-10 11:31:28 +08:00
    entertainyou
        1
    entertainyou  
       2019-10-09 17:47:11 +08:00
    为啥不直接:

    BigDecimal bigDecimal = maps.stream().findFirst().map(m -> (BigDecimal) m.get("totalRecharge")).orElse(0) ?
    qwerthhusn
        2
    qwerthhusn  
       2019-10-09 18:02:14 +08:00
    如果用的是 java 11 的话,可以这样玩
    var xxxRef = new Object() { String xxx; };
    xxxRef.xxx = "123";

    而且这样的话,可以一次性将多个变量括进去。
    如果 JDK10 之前,就用数组吧,但是感觉略奇怪。
    rqxiao
        3
    rqxiao  
    OP
       2019-10-10 11:21:14 +08:00
    @entertainyou 这样子 会有空指针
    rqxiao
        4
    rqxiao  
    OP
       2019-10-10 11:31:28 +08:00
    @rqxiao 额 好像 findFirst()就会出现空指针
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5138 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 01:17 · PVG 09:17 · LAX 18:17 · JFK 21:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.