Sue
Sue

Reputation: 2740

throw exception in lambda - java 8

I'm using lambda expressions. What is the equivalent of this:

for (Integer id: ids) {
    if (!repository.exists(id)) {
        throw new Exception .....
    }
}

I tried using this:

ids.stream().filter(id-> repository.exists(idStatut)).findAny().orElseThrow(() ->
                new Exception...
            );

But it doesn't work well

Upvotes: 2

Views: 367

Answers (1)

Eran
Eran

Reputation: 393791

Based on your original loop, you want to throw an exception if any of the Integers don't pass the filter:

if (ids.stream().anyMatch(id -> !repository.exists(id)))
    throw new Exception ...

Upvotes: 5

Related Questions