Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Map: filter value and throw exception if match found

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.

like image 853
Arpit M Avatar asked Apr 26 '16 15:04

Arpit M


People also ask

Can we use filter and map together in Java 8?

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.

How do I filter a map based on values 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.

How do you throw an exception in Java forEach 8?

forEach(i -> { try { writeToFile(i); } catch (IOException e) { throw new RuntimeException(e); } }); This gets the code to compile and run.


2 Answers

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 ==.

like image 55
rgettman Avatar answered Sep 21 '22 21:09

rgettman


Alternate cleaner solution, using anyMatch:

boolean found = map.values()
                   .stream()
                   .anyMatch(a -> stringToBeMatched.equals(a.getField()));
if(found) {
   throw new IllegalArgumentException();
}
like image 38
Jean Logeart Avatar answered Sep 22 '22 21:09

Jean Logeart