1

I have a List<BigInteger> listBigInt. Some of the items are null some are not.
I want all the items (except the null values) multiplied by five and summed using java8 streams.
So far I fugured out this construct:

BigDecimal sum = listBigInt.stream()
    .map(c -> (c == null ? BigDecimal.ZERO : c).multiply(new BigDecimal(5)))
    .reduce(BigDecimal::add).get();

Is there more elegant way to avoid null values?

George
  • 7,206
  • 8
  • 33
  • 42

2 Answers2

3

You can gain some more speed by multiplying last:

BigDecimal sum = listBigInt.stream()
    .filter(c -> c != null)
    .reduce(BigDecimal::add)
    .get()
    .multiply(new BigDecimal(5));
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34
1

Actually a possible way is to use a filter before the mapping as this:

BigDecimal sum = listBigInt.stream()
    .filter(c -> c != null)
    .map(c -> c.multiply(new BigDecimal(5)))
    .reduce(BigDecimal::add).get();
George
  • 7,206
  • 8
  • 33
  • 42