In the following code:
myList.stream()
.filter(item -> someMethod(item))
.map(item -> doSomething(item))
.collect(Collectors.toList());
How can I throw a RuntimeException
if the result of the filter is a list of size 0 (i.e. no item passes the filter)?
You could use collectingAndThen:
myList.stream()
.filter(item -> someMethod(item))
.map(item -> doSomething(item))
.collect(Collectors.collectingAndThen(Collectors.toList(), result -> {
if (result.isEmpty()) throw new RuntimeException("Empty!!");
return result;
}));
Since there is no straight forward way of How to check if a Java 8 Stream is empty?, a much preferrable code would be :
List<SomeObject> output = myList.stream()
.filter(item -> someMethod(item))
.map(item -> doSomething(item))
.collect(Collectors.toList());
if (!myList.isEmpty() && output.isEmpty()) {
throw new RuntimeException("your message");
}
Another alternative to this could be using noneMatch
, to validate before the execution such as:
if (myList.stream().noneMatch(item -> someMethod(item))) {
throw new RuntimeException("your message");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With