I heard that wechat search “Java fish” will change strong oh!
This article is posted on Github and Gitee, and contains my entire Java series of articles for study and interview purposes
(1) Introduction
In normal coding, there is one error that always pops up unexpectedly, and that is the null-pointer exception. Null Pointers are also very simple, you get a null object, you call some methods, you get a null pointer exception. Null Pointers can appear in a variety of places, common examples being map.get (), which calls methods on an object instance when it doesn’t get an object, and class methods, which call methods on a class object when it doesn’t get an object.
There are many ways to handle null Pointers, the simplest of which is to use if/else nulls, but this can be tedious code. This article will show you how to resolve null pointer exceptions with Optional in JDK8.
(b) What is Optional
The Optional class is a new Java 8 feature. It is a container object that can be null.
Option.of () : Passes the argument, and if the object in of is null, a null pointer exception is reported.
Optional<T> optional = Optional.of()
Copy the code
Option.ofnullable () : Allows ofNullable to pass null objects
Optional<T> optional = Optional.ofNullable();
Copy the code
Option.empty () : Returns an empty Optional instance
Optional<T> optional = Optional.empty();
Copy the code
Option.ispresent () : Checks whether the optional instance is empty
optional.isPresent()
Copy the code
Option.orelse () : Returns the object in orElse if optional is empty
optional.orElse()
Copy the code
Option.get () : Gets the T object in optional
optional.get();
Copy the code
Option.map () : If optional is not null, the mapping function in the map method returns the value.
optional.map(Function<? super T,? extends U> mapper)
Copy the code
The next section will demonstrate Optional’s advantage in handling Null values through practical code examples.
(3) Null value judgment of Map set
Nullification of collection types can be quite verbose in some scenarios, such as the one I recently encountered where I received a Map like this:
{"user": {"info": {"address":"hz"}}}
Copy the code
In this case, if you follow the conventional writing method, you need to write multiple if statements to nullify
if (map.get("user")! =null){
Map<String,Object> user = (Map<String, Object>) map.get("user");
if (user.get("info")! =null){
Map<String,Object> info = (Map<String, Object>) user.get("info");
if (info.get("address")! =null){
String address = (String) info.get("address"); System.out.println(address); }}}Copy the code
If has an if inside of it, and it’s very complicated, so we can use Optional
String address=Optional.ofNullable(map)
.map(m->(Map<String,Object>)m.get("user"))
.map(user->(Map<String,Object>)user.get("info"))
.map(info->(String)info.get("address"))
.orElse(null);
Copy the code
(4) Object type empty reference judgment
Let’s start with a simple object:
@Data
public class User {
private UserInfo info;
}
@Data
public class UserInfo {
private String address;
}
Copy the code
Assign a basic value to the User object
User user=new User();
UserInfo userInfo=new UserInfo();
userInfo.setAddress("hz");;
user.setInfo(userInfo);
Copy the code
In general, multiple if/else nulls are required when using User objects, such as the following:
if(user! =null){
UserInfo info = user.getInfo();
if(info! =null){ String address = info.getAddress(); }}Copy the code
Using Optional, you can solve the problem with one line of code:
String address = Optional.ofNullable(user)
.map(u -> u.getInfo())
.map(info -> info.getAddress())
.orElse(null);
Copy the code
(5) Use in common scenarios
Optional can also be used in common scenarios, such as setting a default value when a value is null:
User resultUser = Optional.ofNullable(user).orElse(new User());
Copy the code
Another example is to determine whether an object is empty:
boolean isPresent = Optional.ofNullable(user).isPresent();
Copy the code
(6) Summary
That’s the end of Optional, most of the scenarios are covered, and the rest is up to you. I’m fish boy. See you next time!