How do I type validate values in a map?


I have a Map<String, Object> which I call myMap, and I want to iterate through each key and ensure that its value is either of type String, int & Boolean.

I’ve tried something along these lines:

myMap.entrySet().forEach(key -> myMap.get(key));

I don’t know how to do the actual check…

>Solution :

You can check all of myMap.values() with Stream#allMatch.

boolean pass = myMap.values().stream().allMatch(o -> o instanceof String || 
                    o instanceof Integer || o instanceof Boolean);

Note that it is impossible for the value to be of type int; it can only be the wrapper class Integer.

Leave a Reply Cancel reply