NULL safe object checking in JAVA 8

java 8 check if object is null or empty
java null check best practice
java check if object is null or empty
string null check in java 8
object null check in java
java check parameter not null
null check in lambda expression java
java 8 stream null check

So i want to do a null safe check on a value contained within a value.

So I have 3 objects contained within each other:

Person has a clothes object which has a country object which has a capital

So a person may not have clothes so a check like this throws a null pointer:

if (person.getClothes.getCountry.getCapital)

How would I make a statement like this just return false if any of the objects on the path are null?

I also don't want to do it this way. (A one-liner in Java-8 if possible.

if (person !=null) {
    if (person.getClothes != null) {
        if (person.getClothes.getCountry !=null) {

You can chain all of those calls via Optional::map. I sort of find this easier to read than if/else, but it might be just me


Tired of Null Pointer Exceptions? Consider Using Java SE 8's , Java SE 8 introduces a new class called java.util.Optional that can of null. Let's consider a nested object structure for a Computer , as illustrated in Figure 1. You don't need to write complex nested conditions to check for null. In addition  In this article, we have seen how you can adopt the new Java SE 8 java.util.Optional<T>. The purpose of Optional is not to replace every single null reference in your codebase but rather to help design better APIs in which—just by reading the signature of a method—users can tell whether to expect an optional value.

These "cascade" null-checks are really paranoid and defensive programming. I'd start with a question, isn't better to make it fail fast or validate the input right before it's store into such a data structure?

Now to the question. As you have used nested the null-check, you can do the similar with Optional<T> and a method Optional::map which allows you to get a better control:

        .map(clothes -> clothes.getCountry())
        .map(country -> country.getCapital())
        .orElse(..)                               // or throw an exception.. or use ifPresent(...)

Avoiding Null Checks in Java 8, NullPointerExceptions in Java 8 in order to improve null safety and code system for references in an object oriented language (ALGOL W). We can get rid of all those null checks by utilizing the Java 8 Optional type. The method map accepts a lambda expression of type Function and automatically wraps each function result into an Optional. That enables us to pipe multiple map operations in a row. Null checks are automatically handled under the hood.

You can achieve using single line of code

if (person != null && person.getClothes != null && person.getClothes.getCountry != null) { }

As you know there is substantial difference between = and ==.

The operators && and || are short-circuiting, meaning they will not evaluate their right-hand expression if the value of the left-hand expression is enough to determine the result

If your first expression is true then only it will check for next expression.

If first expression is false then it will not check for next expression.

So as your requirement if person is not null then only check for person.getClothes != null and so on.

Avoid Check for Null Statement in Java, An aggressively safe strategy could be to check null for every object. This, however Java 8 introduced a new Optional API in the language. Java 8 introduced the Optional class to make handling of nulls less error-prone. For example, the following program to pick the lucky name has a null check as:

As you mentioned Java -8 Here is what you would like

Objects.isNull(person) //returns true if the object is null

Objects.nonNull(person) //returns true if object is not-null


By using Optional, and never working with null, you could avoid null checks altogether. Since they aren't needed, you also avoid omitting a null check leading to NPEs. Still, make sure that values returned from legacy code (Map, ...), which can be null, are wrapped asap in Optional. check here

if(Objects.nonNull(person) && Objects.nonNull(person.getClothes) &&  Objects.nonNull(person.getClothes.getCountry )){
   // do what ever u want

And if you are operating with Collections and using org.apache.commons then CollectionUtils.isNotEmpty(persons) and CollectionUtils.isEmpty(persons) will works for you. Where Persons is List of person.

Java 8 Optional: Handling Nulls Properly, In this tutorial, learn how to handle null properties in Java 8 by using the This null check can be replaced with the Optional class method You can read more about immutable objects in my book, Java Coding Problems. The Optional class was added to Java 8 to add a new approach to handling null. Optional is some envelope over a value (functor), in which there can either be a specific value or not. For example, you can do this:

Java 8 Optional, This won't explode, but is just ugly, and it's easy to avoid some null check. Java 8. Let's try with Java 8's Optional: // let's assume  Use '==' to check a variable's value. A '==' is used to check that the two values on either side are equal. If you set a variable to null with '=' then checking that the variable is equal to null would return true. variableName == null; You can also use '!=' to check that a value is NOT equal.

Why use Optional in Java 8+ instead of traditional null pointer checks?, Now, I see applications flooded with Optional objects. Before Java 8 (Style 1) Employee employee = employeeServive.getEmployee();  It is safe : will never be executed if foo == null. It prevents from bad practice such as catching NullPointerExceptions (most of the time due to a bug in your code) It should execute as fast or even faster than other methods (even though I think it should be almost impossible to notice it).

Better null-checking in Java, Robert Brautingham's Why I Never Null Check Parameters is an option (ha ha, get it) is to use the Optional class introduced in Java 8. This is a very common problem for every Java developer. So there is official support in Java 8 to address these issues without cluttered code. Java 8 has introduced java.util.Optional<T>. It is a container that may or may not hold a non-null value. Java 8 has given a safer way to handle an object whose value may be null in some of the cases.

  • One liner: if (person != null && person.getClothes != null && person.getClothes.getCountry != null) { }.
  • What do you want the code to do? Having long chains of methods calls that access different nested objects can also be considered an anti-pattern as it violates the so called Law of demeter (a.k.a. principle of least knowledge).
  • basically, if the value exists(getCountry), take the result of that, otherwise false....
  • So could you add a method to Person asking his/her clothes to tell which country they are from?
  • btw you could accept the answer if it helped you...
  • I think it would be better to refactor the code or even use nested ifs instead of doing it like this..
  • @MickMnemonic I don't know... I actually like it like this, but I might get affected from such much java-8..
  • @MickMnemonic could not agree more, but we have all been there, what if this is not an option?
  • @MickMnemonic the solution would be to refactor the code, indeed. But to not allowing so many properties to be null in the first place. Is there any use in allowing the capital of a country to be null? I don’t think so. The association between clothes and country is above my head anyway…
  • @Holger ... Shoot you maybe right... I never even factored in the case where the person is an exhibitionist and doesn't wear clothes at all, unless you would count socks as clothes?
  • There is no sense in using Objects.nonNull(person) instead of person != null. The method only exists to allow using Objects::nonNull in functional contexts, i.e. when a Predicate is needed.
  • @Holger agrred with your comment , but my answer was more close to a way in java-8 not among which one is best .
  • Using … != null still is the way to do it in Java 8 and even Java 11. Otherwise, it’s like using a smartphone to hammer a nail into the wall, "to show the 2018 way of doing it".
  • @Holger it is not mine personal way , It is still java designers way. Will love to know why i can't use like that . What are the pros and cons of using and not using this.
  • You can use either way, but the preferred way still is the same as before, for ordinary expressions. As said, the nonNull method has been added to allow using it in method references of the Objects::nonNull form. To quote the author himself: "These small methods were specifically added to the APIs so that programmers could use names instead of inline lambdas"…