How do we handle exception in java streams

DarkCrow :

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()));
Andrew Tobilko :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=305599&siteId=1