Reputation: 850
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()));
Upvotes: 3
Views: 161
Reputation: 49606
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.
Upvotes: 3