I wrote a piece of logic in Java 8. My colleagues couldn't understand it directly. You can try it. .

Business background

First of all, the business needs are like this. Pull all orders from the third-party e-commerce platform and save them to the company's own database. It is necessary to determine whether there is logistics information. If there is logistics information, it needs to be uploaded again.

The third party interface returns data JSONformat, wherein the information stream hiding very deep, as shown, JSON node is following:

xxxOrder > xxxShippingInfo > xxxShipmentDetails > xxxTrackingInfo > trackingNumber, trackingLink

Basic realization

Because the third party interface returns data JSONformat, it is necessary to JSONconvert the string into a Java object to be processed.

@JsonIgnoreProperties(ignoreUnknown = true)
public class XxxOrder {

    /**
     * 物流信息
     */
    @JsonProperty("shippingInfo")
    private XxxShippingInfo xxxShippingInfo;

}

The above is only an example of the first layer. To get the logistics information, four layers of objects must be encapsulated in sequence. When the logistics information is actually obtained, to avoid null pointers, you need to judge the four layers to get it, as shown in the example:

if(xxxOrder != null){
    if(xxxOrder.getXxxShippingInfo() != null){
        if(xxxOrder.getXxxShippingInfo().getXxxShipmentDetails() != null){
            if(xxxOrder.getXxxShippingInfo().getXxxShipmentDetails().getXxxTrackingInfo() != null){
                ...
            }
        }
    }
}

Obtaining a piece of logistics information is so troublesome, I am also drunk, and writing this way is too inelegant.

Java 8 implementation

Because I know that Java 8 can handle this type of demand, I never thought of implementing it in the most primitive way, and just implemented it with Java 8:

/**
* 公众号:Java技术栈
/
private String[] getFulfillments(XxxOrder xxxOrder) {
    return Optional.ofNullable(xxxOrder)
            .map((o) -> o.getXxxShippingInfo())
            .map((si) -> si.getXxxShipmentDetails())
            .map((sd) -> sd.getXxxTrackingInfo())
            .map((t) -> new String[]{t.getTrackingNumber(), t.getTrackingLink()})
            .orElse(null);
}

After I finished writing, my colleagues even said they couldn't understand, and even came to ask me. .

Realization principle

In fact, this does not use any superb technology. It is implemented using Java 8 Optional. The details are not introduced. It is mainly for avoiding null pointers. If you don't understand, you can click here to view this article.

Today, I will introduce the principle of the Optional#map method to implement this logic, and look at the source code of map implementation:

public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
    // 函数式接口不能为null
    Objects.requireNonNull(mapper);

    // 如果当前没有值,返回一个空的Optional
    if (!isPresent())
        return empty();
    else {
        // 如果当前有值,返回一个函数式处理该值的结果Optional
        return Optional.ofNullable(mapper.apply(value));
    }
}

// 判断 Optional Value 有没有值
public boolean isPresent() {
    return value != null;
}

// 创建一个 Optional,可以为空
public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}

So back to this program:

// 根对象为空就创建一个空Optional,否则就创建一个根对象的Optional
Optional.ofNullable(xxxOrder)
    // 根对象为空就直接返回空Optional,否则返回这个值的 Optional
    .map((o) -> o.getXxxShippingInfo())
    // 下面依次类推……
    .map((si) -> si.getXxxShipmentDetails())
    .map((sd) -> sd.getXxxTrackingInfo())
    .map((t) -> new String[]{t.getTrackingNumber(), t.getTrackingLink()})
    // 取不到值就返回 null
    .orElse(null);
}

Maybe you still can’t understand it after reading it. I admit that it’s really convoluted and not easy to understand. This can only be unspeakable, and you can understand it by reading and practicing.

The key point of this is that when calling map, if Optional has no value, it will directly return an empty Optional instead of calling the functional interface, so there will be no null pointer. So as long as one of them is empty, no logistics information can be obtained later.

The program uses chained calls like .xx.xx.xx, calling the map method must be Optional, and the return result of map is Optional.

One problem is that if they are all empty, not all maps will go through? Will it affect performance in this case? Does the compiler optimize? This is temporarily unknown.

There is also a flatMapmethod, and mapwhat difference does it make?

flatMap The returned result needs to be encapsulated in a functional interface, which is not suitable for application here.

to sum up

Many people have been saying that they are learning the new features of Java 8, but in my opinion, most people have no practice and use the most primitive implementation.

In fact, I personally have been working hard to learn this knowledge. The latest I have learned Java 14. I have also shared a series of new feature articles before. If you are interested, you can follow the public number Java technology stack and reply to java to get it.

So although I am an old wave now, I feel that I have come before a lot of wave after learning and mastering new knowledge.

There are a lot of techniques to learn to be a Java programmer. Although you have a bit of knowledge in a short time, you understand it, but it is certainly not deep. After a long time, you will forget it. So the advice for everyone is to practice + read the source code, so that it really belongs your.

I think it's good, with the support of watching and forwarding~

Recommend to read more on my blog:

1. A series of tutorials on Java JVM, collections, multithreading, and new features

2. Spring MVC, Spring Boot, Spring Cloud series of tutorials

3. Maven, Git, Eclipse, Intellij IDEA series tool tutorial

4. The latest interview questions from major manufacturers such as Java, back-end, architecture, and Alibaba

Feel good, don’t forget to like + forward!

Finally, pay attention to the WeChat official account of the stack leader: Java technology stack, reply: Welfare, you can get a free copy of the latest Java interview questions I have compiled for 2020. It is really complete (including answers), without any routine.

Guess you like

Origin blog.csdn.net/youanyyou/article/details/108376271