0

Hi2 all!

I have the following code:

    statusLiquidationsFromPegaDictionary.
                stream()
                .filter(statusLiquidation -> statusCode.equals(statusLiquidation.getId()))
                .anyMatch(statusLiquidation -> statusLiquidation.getDecl().equals("N"));

Right now I'm getting an empty list after filtering. I'd like to throw an exception in that case instead. Can I do this in the same stream?

Naman
  • 27,789
  • 26
  • 218
  • 353
Alexandr
  • 5
  • 3
  • Does this answer your question? [Java 8: Lambda-Streams, Filter by Method with Exception](https://stackoverflow.com/questions/19757300/java-8-lambda-streams-filter-by-method-with-exception) – Arun Sudhakaran Dec 17 '19 at 13:50
  • You don't get "an empty list after filtering". That's not how streams work. You just don't get an element matching both predicates. – Holger Dec 17 '19 at 14:30
  • yes, after filtering in stream may be 0 elements, and anyMatch no need to call, i whant throw exception – Alexandr Dec 17 '19 at 14:43
  • No, you are still thinking wrong about [how streams work](https://stackoverflow.com/a/35157305/2711488). There is no "after filtering". Each element is checked against the filter predicate and if it matches, it is checked against the anyMatch predicate. If it matches too, the operation ends without having checked all elements against the filter predicate. Exactly as if you specified `statusLiquidationsFromPegaDictionary.stream().anyMatch(statusLiquidation -> statusCode.equals(statusLiquidation.getId())&&statusLiquidation.getDecl().equals("N"));` No difference. – Holger Dec 17 '19 at 17:04

1 Answers1

0

If you really want to throw an exception if no elements match the first filter (as you mention in the comments), you will have to do it in 2 steps:

final List<StatusLiquidation> withCorrectStatus = statusLiquidationsFromPegaDictionary
        .stream()
        .filter(statusLiquidation -> statusCode.equals(statusLiquidation.getId()))
        .collect(toList());

if (withCorrectStatus.isEmpty()) {
    throw new Exception("Nothing found");
}

return withCorrectStatus.stream()
        .anyMatch(statusLiquidation -> statusLiquidation.getDecl().equals("N"));
Ward
  • 2,799
  • 20
  • 26