Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we handle exception in java streams

How can I convert this for loop using the stream.

for (final Foo foo : fooList) {
    if (!FooConstant.FOO_TYPE.equals(foo.getType())) {
        throw new BadRequestException(
          LOGGER,
          FooErrorEnum.NOT_FOO_TYPE.name(),
          String.format("Element %s is not Foo type", foo.getId())
        );
    }
}

I tried doing this way but the foo.getId() is not available in orElseThrow(). Note: BadRequestException is checked exception.

fooList.stream().filter(foo -> !FooConstant.FOO_TYPE.equals(foo.getType())
    .findFirst()
    .orElseThrow(() -> new BadRequestException(LOGGER, FooErrorEnum.NOT_FOO_TYPE.name(), String.format("Element %s is not Foo type", foo.getId()));
like image 202
DarkCrow Avatar asked Mar 28 '26 17:03

DarkCrow


1 Answers

You need Optional#ifPresent.

fooList.stream().filter(foo -> !FooConstant.FOO_TYPE.equals(foo.getType())
                .findFirst()
                .ifPresent(foo -> {
                     throw new BadRequestException(LOGGER, FooErrorEnum.NOT_FOO_TYPE.name(), String.format("Element %s is not Foo type", foo.getId())
                });

It's weird, though. We usually use Optional the other way around: to filter out invalid options and find the first valid one. In your example, orElseThrow would be executed when everything is fine, so no exception should be thrown.

Note that BadRequestException must be a RuntimeException, otherwise it won't compile.

like image 184
Andrew Tobilko Avatar answered Mar 30 '26 11:03

Andrew Tobilko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!