I'm working on a request validation feature where I need to check if a certain string value is present in a property that is contained in an object, which is contained as a value of a map entry, that map is a part of an object and finally my request body contains a set of those objects.
To try and make it clearer I will recreate my situation using only parts of code that are important.
Lets say my ClassA is received in request body, it has following properties:
@Nullable
Set<ClassB> mySet = null;
Now, we have ClassB that has a certain wrapper object of type ClassC:
@Nullable
ClassC classC;
That wrapper class ClassC contains a map:
@Nullable
Map<String, ClassD> classDMap = new HashMap<>;
Finally, ClassD contains the property that needs to be checked if it contains a certain value:
@Nullable
String propertyForValidation;
At the moment I went with code that looks like this:
public boolean isValid(ClassA body) {
return body.getMySet().stream()
.allMatch(x -> x.getClassC().getClassDMap().values().stream()
.allMatch(y -> y.getPropertyForValidation.equals("someValue"));
}
Current problem with my code is that it does not work as expected when some objects that I've described above are null since I'm getting a lot of NullPointerExceptions. I suppose this can be resolved with a lot ifs and null checks, but I was wondering if there is a more elegant way of doing it using Stream API?
All help is appreciated, thanks.