0

I'm a relatively novice Stream user and I feel like there should be a cleaner way to accomplish what I have below. Is it possible to accomplish what the code below does all within a single Stream (eliminating the if/else at the bottom)?

Thanks!

Optional<SomeMapping> mapping = allMappings.stream()
     .filter(m -> category.toUpperCase().trim().equalsIgnoreCase(m.getCategory().toUpperCase().trim()))
     .findAny();         
if (mapping.isPresent()) {
     return mapping.get();
} else {
     throw new SomeException("No mapping found for category \"" + category + "\.");
}
Naman
  • 27,789
  • 26
  • 218
  • 353
WishIWasJeeping
  • 173
  • 2
  • 11

2 Answers2

5

Use orElseThrow to throw an exception if the Optional is empty:

return
    allMappings.stream()
               .filter(m -> category.trim().equalsIgnoreCase(m.getCategory().trim()))
               .findAny()
               .orElseThrow(() -> new SomeException("No mapping found for category \"" + category + "\"."));
Holger
  • 285,553
  • 42
  • 434
  • 765
Eran
  • 387,369
  • 54
  • 702
  • 768
1

No need to use toUpperCase() as you are comparing with equalsIgnoreCase().

return allMappings.stream().filter(m -> category.trim().equalsIgnoreCase(m.getCategory().trim()))
                       .findAny()
                       .orElseThorw (() -> new SomeException("No mapping found for category \"" + category + "\."));
Ullas Sharma
  • 450
  • 11
  • 22
  • Now that there is [an edit](https://stackoverflow.com/revisions/60191230/4) on the other answer and otherwise as well the suggestion that you're making should be a comment and not an answer. – Naman Feb 12 '20 at 16:17
  • Derp, thanks for pointing that out! – WishIWasJeeping Feb 12 '20 at 16:27