繁体   English   中英

避免在使用lambda表达式对值集合执行算术运算时抛出java.lang.NullPointerException

[英]Avoiding a java.lang.NullPointerException being thrown while performing arithmetic operations on a collection of values using lambda expressions

给出要总结的值列表。

List<CartItems> cartItems = ...

BigDecimal totalWeight = cartItems.stream().reduce(BigDecimal.ZERO, (weight, cart)
        -> weight.add(cart.getProduct().getWeight().multiply(BigDecimal.valueOf(cart.getQty()))), BigDecimal::add)
        .setScale(SCALE, RoundingMode.HALF_UP);

这里, cart.getProduct().getWeight()可以随时为null ,因为它是一个可选字段。 因此,如果其中一个项在java.math.BigDecmial类型的weight字段中包含null值,则会抛出java.lang.NullPointerException

什么是最简洁的方法来避免当给定集合中的项包含null值而不是强制执行如下所述的恶意条件检查时抛出java.lang.NullPointerException

BigDecimal totalWeight = products.stream().reduce(BigDecimal.ZERO, (weight, cart)
        -> weight.add(cart.getProduct().getWeight() == null ? BigDecimal.ZERO : cart.getProduct().getWeight().multiply(BigDecimal.valueOf(cart.getQty()))), BigDecimal::add)
        .setScale(SCALE, RoundingMode.HALF_UP);

类似地,以下内容也将抛出java.lang.NullPointerException ,因为给定的列表中包含null值。

List<Integer> list = new ArrayList<Integer>() {{
        add(1);
        add(2);
        add(3);
        add(null);
        add(5);
    }};

Integer sum = list.stream().reduce(0, Integer::sum); // Or
//Integer sum = list.stream().reduce(0, (a, b) -> a + b);

System.out.println("sum : " + sum);

我认为问题更多的是减少。 你尝试在一个函数中做很多事情。 据我了解,你想要每辆车的weight*qty总和。 我会像这样削减操作:

BigDecimal totalWeight = cartItems.stream()
        .filter(cart -> cart != null
                && cart.getProduct() != null 
                && cart.getProduct().getWeight() != null)
        .map(cart -> cart.getProduct().getWeight().multiply(BigDecimal.valueOf(cart.getQty())))
        .reduce(BigDecimal.ZERO, BigDecimal::add)
        .setScale(SCALE, RoundingMode.HALF_UP);

以下是针对此问题的几种解决方案。

        List<Integer> list = Arrays.asList(new Integer[]{
                1,
                2,
                3,
                (Integer)null,
                5,
        });

        Integer sum = list.stream().map(i -> i != null ? i : 0).reduce(0, Integer::sum); 

要么

list.replaceAll(s -> s == null ? 0 : s);
Integer sum = list.stream().reduce(0, Integer::sum);

你可以这样做:

Integer sum = list.stream().filter(Objects::nonNull).reduce(0, Integer::sum);

再见!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM