As a programmer, you certainly come across NullPointerException, the exception for fledgling newcomer or seasoned veteran rivers and lakes are inevitable pain, and yet is so powerless, in order to solve it, you can only use a certain value before its empty sentenced to treatment. However, this would make the code bloat. Fortunately jdk8 optional introduced to deal with the problem of null, null no longer allows us to do too much concern.
Written before the first show of jdk8
If the user does not get a method for determining empty, the following properties can easily get its null pointer exception.
jdk 8 wording
Such an approach would avoid the empty judgment, the code is very simple
The method described below under the optional
1, first configuration of, ofNullable, empty
Look ofNullable source method
2, get ifPresent, get, isPresent
Examples of the beginning of such a change can also be used isPresent, but this original sentence and empty and there is no difference, but the method is different, in essence, no difference, it is not recommended. Look at the source code of these methods
3, get orElse, orElseGet, orElseThrow
Look at the source code
Similarly orElseThrow
4, filtration filter
5, the conversion map, flatMap
看源码知道,map 和 flatmap 都是如果optional中的值存在,就对该值执行提供的Function函数调用,返回一个optional类型的值,否
则就返回一个空的optional对象。
The biggest difference is after the map function to perform any type of data, and then call the end of the map will be optional on the results of the package, and is a flatmap is optional instance After you have performed, the results will not flatmap optional package.