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()));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With