The return value of "orElseThrow" must be used

Baji Shaik :

When I am scanning code with sonar lint the following code shows the bug as "The return value of "orElseThrow" must be used"

itemList.stream()
    .filter(item -> orderItemId.equals(item.getId()))
    .findAny()
    .orElseThrow(() -> new BadRequestException("12345","Item Not Found"));

This is just for a validation purpose no need to return anything from this statement. need to validate whether the item exists or not.

FYI: Eclipse showing a quick fix as squid:S2201

Anybody have any idea how to resolve this bug?

Eran :

I'm assuming this is a warning (not using the value returned by orElseThrow() shouldn't be an error).

If you wish to eliminate that warning, use isPresent() instead:

if (!itemList.stream().filter(i->orderItemId.equals(i.getId())).findAny().isPresent()) {
    throw new BadRequestException("12345","Item Not Found");
}

or just avoid using Optionals, and use anyMatch() instead:

if (!itemList.stream().anyMatch(i->orderItemId.equals(i.getId()))) {
    throw new BadRequestException("12345","Item Not Found");
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=436172&siteId=1