3

How to filter stream expression to throw exception?

I have function to check sum of list elements, if sum is more than 1 -> throw exception

Double sum = list.stream().map(element::getNumber).reduce(0.0,Double::sum);
if(sum>1){
   throw new Exception("message);
}

Is it possible to add if condition to stream expression to get rid of the additional if condition?

SternK
  • 11,649
  • 22
  • 32
  • 46
Max
  • 253
  • 2
  • 16

2 Answers2

9

You could make use of the single argument Stream.reduce() and Optional.orElseThrow()

list.stream()
    .map(element::getNumber)
    .reduce(Double::sum)
    .filter(sum -> sum <= 1)
    .orElseThrow(() -> new Exception("message"));
Lino
  • 19,604
  • 6
  • 47
  • 65
2

You can do it inside of the reduce operation, the downside is that you can't use a checked exception natively, but you can find workarounds to still throw a checked exception inside of a lambda

Double sum = list.stream()
                 .map(element::getNumber)
                 .reduce(0.0, (first, second) -> {
                     double s = first + second;
                     if (s > 1) throw new RuntimeException("");
                     return s;
                 });
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89