• 请不要在回答技术问题时复制粘贴 AI 生成的内容
rqxiao
V2EX  ›  程序员

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

  •  
  •   rqxiao · Oct 9, 2019 · 3429 views
    This topic created in 2425 days ago, the information mentioned may be changed or developed.

        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 replies    2019-10-10 11:31:28 +08:00
    entertainyou
        1
    entertainyou  
       Oct 9, 2019
    为啥不直接:

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

    而且这样的话,可以一次性将多个变量括进去。
    如果 JDK10 之前,就用数组吧,但是感觉略奇怪。
    rqxiao
        3
    rqxiao  
    OP
       Oct 10, 2019
    @entertainyou 这样子 会有空指针
    rqxiao
        4
    rqxiao  
    OP
       Oct 10, 2019
    @rqxiao 额 好像 findFirst()就会出现空指针
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2873 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 04:09 · PVG 12:09 · LAX 21:09 · JFK 00:09
    ♥ Do have faith in what you're doing.