I have the below code which is bit ugly for multiple null checks.
String s = null; if (str1 != null) { s = str1; } else if (str2 != null) { s = str2; } else if (str3 != null) { s = str3; } else { s = str4; }
So I tried using Optional.ofNullable
like below, but its still difficult to understand if someone reads my code. what is the best approach to do that in Java 8.
String s = Optional.ofNullable(str1) .orElse(Optional.ofNullable(str2) .orElse(Optional.ofNullable(str3) .orElse(str4)));
In Java 9, we can use Optional.ofNullable
with OR
, But in Java8 is there any other approach ?
Java 8 introduced an Optional class which is a nicer way to avoid NullPointerExceptions. You can use Optional to encapsulate the potential null values and pass or return it safely without worrying about the exception. Without Optional, when a method signature has return type of certain object.
With the release of Java 8, a straight-forward way of handling null references was provided in the form of a new class: java. util. Optional<T> . It's a thin wrapper around other objects, so you can interact with the Optional instead of a null reference directly if the contained object is not present.
From the documentation : Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1. equals(e2), and they typically allow multiple null elements if they allow null elements at all.
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.
However, notice the writing is no easier than: The Optional class, however, supports other techniques that are superior to checking nulls. The above code can be re-written as below with orElse () method as below:
We have to write a bunch of null checks to make sure not to raise a NullPointerException: 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.
Here, we can use Java Assertions instead of the traditional null check conditional statement: public void accept(Object param) { assert param != null ; doSomething (param); } In line 2, we check for a null parameter. If the assertions are enabled, this would result in an AssertionError.
You may do it like so:
String s = Stream.of(str1, str2, str3) .filter(Objects::nonNull) .findFirst() .orElse(str4);
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