Validate request object which is a MutableMap(Map) throw exception if it's value is NULL

37 Views Asked by At

I have a MutableMap(map) as below in a function, let’s assume we have N no.of entries in it. I need to validate values in the map and throw exception with key if it is a Null. Please provide some suggestions on how to achieve using streams of java -8

fun validateRequest (map :  MutableMap<String, Array<String>>)
1

There are 1 best solutions below

0
On
Map<String, List<String>> map = new HashMap<>();
map.put("1", new ArrayList<>());
map.put("2", new ArrayList<>());
map.put("3", null);
map.put("4", new ArrayList<>());
map.put("5", null);
String s = map.entrySet().stream().filter(entry -> entry.getValue() == null).map(Map.Entry::getKey).collect(Collectors.joining(","));
if (!s.isEmpty()) {
    throw new RuntimeException("{" + s + "} keys are with null values");
}

I have tested this code and it works used JDK 1.8 that was my result

Exception in thread "main" java.lang.RuntimeException: {3,5} keys are with null values