Antecedents feed

Your girlfriend suddenly takes out a bag in front of you and asks you what brand is this bag? What do you do? Write some code and print it, of course.

public class Boy {
    // a new girlfriend
    private GirlFriend girlFriend;

    public GirlFriend getGirlFriend(a) {
        returngirlFriend; }}public class GirlFriend {
    A girlfriend is a cure-all
    private Bag bag;

    public Bag getBag(a) {
        returnbag; }}public class Bag {
    // Gucci or Prada is up to you
    private String name;

    public String getName(a) {
        returnname; }}class Test {
    // Print the name of your girlfriend's bag
    public String getGirlFriendBagName(Boy boy) {
        returnboy.getGirlFriend().getBag().getName(); }}Copy the code

When you happily implement this method, something unexpected happens to you.

Exception in thread "main" java.lang.NullPointerException
	at com.yideng.Test.getGirlFriendBagName(Boy.java:33)
	at com.yideng.Test.main(Boy.java:38)
Copy the code

// Print the name of your girlfriend's bag
public String getGirlFriendBagName(Boy boy) {
    if(boy ! =null) {
        if(boy.getGirlFriend() ! =null) {
            if(boy.getGirlFriend().getBag() ! =null) {
                returnboy.getGirlFriend().getBag().getName(); }}}return null;
}
Copy the code

Layers of judgment empty, you are a good programmer, certainly don’t like so redundant code, is there a solution? That’s where Optional comes in.

1. What is Optional

The Optional class is just a simple encapsulation of classes, nothing special

public final class Optional<T> {
    ...
}
Copy the code

2. How to create the Optional class

2.1 Declare an empty Optional

Optional<Boy> optBoy = Optional.empty();
Copy the code

In this case, optBoy is equivalent to NULL, but NullPointerException is not reported when optBoy is used

2.2 Create a non-empty Optional

Optional<Boy> optBoy = Optional.of(boy);
Copy the code

If boy is null, NullPointerException is reported

Create an Optional that accepts null

Optional<Boy> optBoy = Optional.ofNullable(boy);
Copy the code

If boy is null, no error is reported.

How to use the Optional class

3.1 Extracting attributes of the Optional object

Optional<GirlFriend> girlFriend = 
                optBoy.map(Boy::getGirlFriend);
Copy the code

In this case, you can pass a Function to handle the object, just as you can in a stream.

3.2 Detect empty objects in advance

optBoy.ifPresent(boy -> System.out.println(boy));
Copy the code

If optBoy is Optional. Empty (), the later print method is not executed.

3.3 Extract null method into if statement

if (optBoy.isPresent()) {
    System.out.println(optBoy);
}
Copy the code

If optBoy is Optional. Empty (), isPresent returns false, and the if statement is not executed.

3.4 Obtaining the Optional Object Attribute Value

Boy boy = optBoy.get();
Copy the code

If optBoy is Optional. The empty () throws an exception Java. Util. NoSuchElementException: No value to the present

3.5 Default values for properties

Boy boy = optBoy.orElse(new Boy());
Copy the code

If optBoy is not Optional. Empty (), return it directly, otherwise return the default new Boy().

3.6 Filtering Optional objects

Boolean isGucci = optbag.filter (bag ->!"Gucci".equals(bag.getName()))
                .isPresent();
Copy the code

4. Use Optional to rewrite the original method

public String getGirlFriendBagName(Optional<Boy> optBoy) {
    return optBoy.map(Boy::getGirlFriend)
            .map(GirlFriend::getBag)
            .map(Bag::getName)
            .orElse("Gucci");
}
Copy the code

Is that a lot more elegant? That’s it. That’s all Optional has.