Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw exception if filter returns a list of size 0

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)?

like image 771
Arian Avatar asked Sep 24 '19 18:09

Arian


2 Answers

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;
            }));
like image 137
Dani Mesejo Avatar answered Nov 17 '22 13:11

Dani Mesejo


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");
}
like image 1
Naman Avatar answered Nov 17 '22 15:11

Naman