Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Objects.requireNonNullElse() and Optional.ofNullable().orElse()?

Java 9 introduces the requireNonNullElse and requireNonNullElseGet methods to the Objects class. Are these functionally any different to the Optional.ofNullable() orElse() and orElseGet() methods?

String foo = null;
Objects.requireNonNullElse(foo, "nonNull");//returns the string "nonNull"
Optional.ofNullable(foo).orElse("nonNull");//also returns the string "nonNull"

If they have no functional difference, why was the Objects one added now?

like image 996
David says Reinstate Monica Avatar asked Oct 02 '17 03:10

David says Reinstate Monica


People also ask

What is optional ofNullable?

What is the ofNullable() method of the Optional class? The ofNullable() method is used to get an instance of the Optional class with a specified value. If the value is null , then an empty Optional object is returned.

Why use Optional instead of null check?

In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional class forces you to think about the case when the value is not present.

What does optional of do in Java?

The of() method of java. util. Optional class in Java is used to get an instance of this Optional class with the specified value of the specified type. Parameters: This method accepts value as parameter of type T to create an Optional instance with this value.


1 Answers

There is one minor difference in their behavior. Objects.requireNonNullElse() requires that one of the parameters be non-null, otherwise, a NullPointerException is thrown.

String foo = null, bar = null;
Optional.ofNullable(foo).orElse(bar); //returns a null value
Objects.requireNonNullElse(foo, bar); //throws a NullPointerException
like image 94
David says Reinstate Monica Avatar answered Sep 30 '22 09:09

David says Reinstate Monica