代码之家  ›  专栏  ›  技术社区  ›  menteith

使用流初始化对象

  •  3
  • menteith  · 技术社区  · 6 年前

    我有一个 Long value 根据某个列表的某个字段是否为空,应将其设置为空,如果找不到空,则应将其设置为列表中这些字段的总和。

    请参阅我的(工作代码)实现这一点:

    Long usedBytes = bdList.stream()
                           .anyMatch(bd -> bd.getBytes() == null) ? 
                     null :
                     bdList.stream()
                           .mapToLong(Backup::getBytes)
                           .sum();
    

    我想知道为什么相似和更简单的代码不能设置 Long usedBytes 当有一个空值作为其字段之一时为空。在这种情况下 Long totalUsedSpace 设置为 0L .

    Long totalUsedSpace = bdList.stream().filter(bd -> bd.bd.getBytes() != null)
                                          .mapToLong(Backup::getBytese)
                                          .sum();
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   Eran    6 年前

    LongStream sum long Long null 0

    Stream

    Long usedBytes = bdList.stream ()
                           .reduce (Long.valueOf (0),
                                    (sum,bd) -> sum == null || bd.getBytes() == null ? null : sum + bd.getBytes(),
                                    (sum1,sum2) -> sum1 == null || sum2 == null ? null : sum1 + sum2);
    

    List<String> strlist = Arrays.asList ("One","Two","Three");
    Long sumOfLengths = strlist.stream ()
                               .reduce (Long.valueOf (0),
                                        (sum,s) -> sum == null || s == null ? null : sum + s.length(),
                                        (sum1,sum2) -> sum1 == null || sum2 == null ? null : sum1 + sum2);
    System.out.println (sumOfLengths);
    

    11
    

    List<String> strlist = Arrays.asList ("One",null,"Two","Three");
    

    null