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.
Once we have the Stream of Integer, we can apply maths to find the even numbers. We passed that condition to filter method. If we needed to filter on String, e.g. select all string which has length > 2, then we would have called filter before map. That's all about how to use map and filter in Java 8.
We can filter a Map in Java 8 by converting the map. entrySet() into Stream and followed by filter() method and then finally collect it using collect() method.
forEach(i -> { try { writeToFile(i); } catch (IOException e) { throw new RuntimeException(e); } }); This gets the code to compile and run.
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 ==
.
Alternate cleaner solution, using anyMatch
:
boolean found = map.values()
.stream()
.anyMatch(a -> stringToBeMatched.equals(a.getField()));
if(found) {
throw new IllegalArgumentException();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With