This might look like a primitive question or a this could be done by a simple utility library method that I don't know about.
The goal is to check the value of a boolean field that is nested under two objects.
private boolean sourceWebsite(Registration registration) { Application application = registration.getApplication(); if (application == null) { return true; } Metadata metadata = application.getMetadata(); if (metadata == null) { return true; } Boolean source = metadata.getSource(); if (source == null) { return true; } return !source; }
I know this could be done in a single if()
. I have added multiple if
s here for the sake of readability.
Is there a way that we could simplify the above if
statements and have a simple utility class that returns the value of Boolean source
if the parent objects or not null?
isEmpty(< string >) Checks if the <string> value is an empty string containing no characters or whitespace. Returns true if the string is null or empty.
All you need to do is to call equals() method on empty String literal and pass the object you are testing as shown below : String nullString = null; String empty = new String(); boolean test = "". equals(empty); // true System.
Java String isEmpty() Method The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.
To check if an array is empty or not, you can use the . length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not.
In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator.
Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string. isEmpty() || string.
You can use java.util.Optional
in this way:
private boolean sourceWebsite(Registration registration) { return Optional.of(registration) .map(Registration::getApplication) .map(Application::getMetadata) .map(Metadata::getSource) .map(source -> !source) .orElse(Boolean.TRUE); }
In short, this will return true
if any of the getters returns null, and !Metadata.source
otherwise.
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