3

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()));
DarkCrow
  • 785
  • 2
  • 8
  • 29

1 Answers1

3

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.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • What if its checked exception? How do we use orElseThrow? – DarkCrow Oct 04 '19 at 15:13
  • @Deepak you can't throw a checked exception from either `ifPresent` or `orElseThrow`. Read this please: https://stackoverflow.com/questions/27644361/how-can-i-throw-checked-exceptions-from-inside-java-8-streams – Andrew Tobilko Oct 04 '19 at 15:27
  • So in this case I can only use for loop ? – DarkCrow Oct 04 '19 at 15:30
  • 1
    @Deepak yes (if you want to throw a checked exception from `ifPresent`). You could throw an unchecked exception from the lambda, intercept it by a try-catch block surrounding `fooList.stream()` and rethrow a checked one, but it's too much. A simple loop is always better. – Andrew Tobilko Oct 04 '19 at 15:35