27

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?

Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78
Baji Shaik
  • 1,022
  • 2
  • 10
  • 14
  • 1
    Thank you @ Aominè for the solution. if(itemList.stream().noneMatch(i->orderItemId.equals(i.getId()))){ throw new BadRequestException("12345","Item Not Found"); } – Baji Shaik Mar 28 '18 at 12:33

1 Answers1

23

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");
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Using empty() seems not the correct way.How ever the second option anyMatch() is the perfect solution for this.Thank you. – Baji Shaik Mar 28 '18 at 11:17
  • 9
    for the first solution, I believe you're looking for `!itemList.stream().filter(i->orderItemId.equals(i.getId())).findAny().isPresent()` but the better solution would be to use `itemList.stream().noneMatch(i->orderItemId.equals(i.getId()))` – Ousmane D. Mar 28 '18 at 11:28
  • @Aominè yep, for some reason I was sure there was an `empty()` method that indicates whether an existing Optional is empty. – Eran Mar 28 '18 at 11:31
  • 6
    …and eliminate the *logical not* by using `noneMatch` in the first place. – Holger Mar 28 '18 at 12:09
  • 5
    My opinion is that this is not a solution changing your code with a simply `orElseThrow` to something else only because a false positive warning. – Saljack Aug 26 '20 at 14:10