7

I have defined this stream:

public int sumNumbers(int[] numbers) {
    return IntStream.of(numbers)
            .filter(n -> n <= 1000)
            .sum();
}

Where I'm summing all integers that are not higher than 1000. But now what I want to do is, throw an exception if any element of the array is negative.

I know how to do it in the old fashioned mode, but I was wondering if there's any mechanism with Stream and .filter() where I can define a filter and an exception case for that filter

Just to clarify I want to throw an exception, and not control a runtime exception as the other question does.

The idea here is that if my filter is true in:

filter(n -> n < 0 throw Exception)
Edd
  • 3,724
  • 3
  • 26
  • 33
paul
  • 12,873
  • 23
  • 91
  • 153
  • 3
    Why not use `n >= 0 && n <= 1000`? Also, `Functional` by default doesn't support throwing checked exceptions. – Luiggi Mendoza Aug 22 '15 at 17:50
  • The requirement it´s throw an exception to inform the wrong data, kinda weird that being so powerful does not allow something like this. – paul Aug 22 '15 at 17:55
  • 1
    @TagirValeev you should post that comment as an answer (except `.peek(n -> {if (n < 0) throw new IllegalArgumentException("" + n);}` is what OP wants) – Bohemian Aug 23 '15 at 11:03
  • @Bohemian, sounds reasonable. Done. – Tagir Valeev Aug 23 '15 at 11:20
  • It’s not always the best to do everything in one operation. A good old pre-check is not bad. If it should be done with streams, you may use: `if(Arrays.stream(numbers).reduce((a,b) -> a|b).orElse(0)<0) throw new IllegalArgumentException();` – Holger Aug 24 '15 at 09:05
  • If you *expect* negative numbers, you can simply test using `Arrays.stream(numbers).anyMatch(i -> i<0)`, but as we are talking about illegal arguments here, I wouldn’t consider them to be expected… – Holger Aug 24 '15 at 09:07

1 Answers1

10

There's an IllegalArgumentException in JDK which is unchecked and informs about wrong function input, so it can be used here:

IntStream.of(numbers)
         .peek(n -> {
           if (n < 0) throw new IllegalArgumentException(String.valueOf(n));
         })
         .sum();

In general, currently Java develops towards unchecked-only exceptions. There's even UncheckedIOException class added in Java-8!

Bohemian
  • 412,405
  • 93
  • 575
  • 722
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334