The tool option handles non empty judgments

Posted by techek on Sun, 23 Jan 2022 11:24:14 +0100

In normal coding, there is an error that always occurs unexpectedly, that is, null pointer exception. The appearance of null pointer is also very simple. You get a null object, call some methods, and a null pointer exception occurs. Null pointers can appear in various places, such as map Get () calls the method of the object instance without getting the object, and calls the method in the class without getting the class object.

There are many ways to handle null pointers. The simplest way is to use if/else to judge null, but the code will be particularly cumbersome. This article takes you to use the Optional in JDK8 to solve the null pointer exception.

What is Optional

The Optional class is a new feature of Java 8. It is easy to use. Several common methods are introduced:

1,Optional.of(): pass parameters. If the object in of is null, null pointer exception will be reported.

Optional<T> optional = Optional.of()

2,Optional.ofNullable(): allow ofNullable to pass null objects

Optional<T> optional = Optional.ofNullable();

3,Optional.empty(): returns an empty optional instance

Optional<T> optional = Optional.empty();

4,optional.isPresent(): judge whether the Optional instance is empty

optional.isPresent()

5,optional.orElse(): returns the object in orElse if optional is empty

optional.orElse()

6,optional.get(): get T object in optional

optional.get();

7,optional.map(): if the optional is not null, execute the mapping function in the map method to get the return value.

optional.map(Function<? super T,? extends U> mapper)

Map set null judgment

The empty judgment of collection type is very verbose in some scenarios, such as a scenario I just met recently. The received Map is as follows:

{"user":{"info":{"address":"hz"}}}

In this case, if you follow the conventional writing method, you need to write multi-layer if statements to judge null:

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);
        }
    }
}

If is nested with if, and the structure is very complex. At this time, 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);

Object type null finger judgment

First, construct a simple object:

@Data
public class User {
    private UserInfo info;
}

@Data
public class UserInfo {
    private String address;
}

Assign basic values to the User object

User user=new User();
UserInfo userInfo=new UserInfo();
userInfo.setAddress("hz");;
user.setInfo(userInfo);

Generally, when using User objects, you need to use multi-layer if/else null judgment, as follows:

if (user!=null){
    UserInfo info = user.getInfo();
    if (info!=null){
        String address = info.getAddress();
    }
}

With Optional, you can solve the problem in one line of code:

String address = Optional.ofNullable(user)
        .map(u -> u.getInfo())
        .map(info -> info.getAddress())
        .orElse(null);

Use in common scenarios

Optional can also be used in normal scenarios, such as setting the default value when a value is empty:

User resultUser = Optional.ofNullable(user).orElse(new User());

Another example is to judge whether an object is empty:

boolean isPresent = Optional.ofNullable(user).isPresent();

 

Topics: Java