How Optional.ofNullable handles null pointers
This article will explain in detail how to deal with null pointers in Optional.ofNullable. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
For null detection of Integer, you can use Optional.ofNullable to construct an Optional
Then use orElse (0) to replace null with the default value and then do the + 1 operation.
For String and literal comparisons, you can put literals first
Such as "OK" .equals (s), so that even if s is null, there is no null pointer exception.
For the equals comparison of two string variables that may be null
You can use Objects.equals, which will do null processing.
For ConcurrentHashMap, since neither its Key nor Value supports null, the fix is not to save the null.
Key and Value of HashMap can be stored in null
While ConcurrentHashMap appears to be a thread-safe version of HashMap, it does not support Key and Value with null values.
This is a place prone to misunderstanding.
For cascading calls like fooService.getBarService (). Bar (). Equals ("OK")
There are many things that need to be null, including the return value of the fooService, getBarService () method, and the string returned by the bar method.
It may take several lines of code to use if-else to determine null
But with Optional, one line of code is enough.
For the List returned by rightMethod
Cannot confirm whether it is null or not
So before calling the size method to get the list size, you can also use Optional.ofNullable to wrap the return value
Then use .orElse (Collections.emptyList ()) to get an empty List when List is null, and finally call the size method.
This is the end of the article on "how to deal with null pointers in Optional.ofNullable". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.