18

I'm trying to find a matching value in a Map and if found, I need to throw an IllegalArgumentException. My code is as follows:

final String stringToBeMatched = "someRandomString"; 

map.values()
   .stream()
   .filter(a -> stringToBeMatched == a.getField())
   .findAny()
   .ifPresent(a -> throw new IllegalArgumentException());

I get a syntax error on token "throw". I'm not sure where I'm going wrong.

argo
  • 381
  • 1
  • 5
  • 15

3 Answers3

31

A lambda body can be an expression or a block of statements. However,

throw new IllegalArgumentException()

is a statement, which is neither. Make it a block by surrounding it with braces.

.ifPresent(a -> {throw new IllegalArgumentException(); } );

And for your next question, compare your string values with .equals, not with ==.

rgettman
  • 176,041
  • 30
  • 275
  • 357
4

Alternate cleaner solution, using anyMatch:

boolean found = map.values()
                   .stream()
                   .anyMatch(a -> stringToBeMatched.equals(a.getField()));
if(found) {
   throw new IllegalArgumentException();
}
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • If you're going to write additional code outside the loop, why not just make a function that raises the exception? – EndermanAPM Feb 07 '19 at 02:26
2

findAny return a Optional, you can use orElseThrow

map.values()
   .stream()
   .filter(a -> stringToBeMatched == a.getField())
   .findAny()
   .orElseThrow(() -> new IllegalArgumentException());
lozanoco
  • 37
  • 1