I used - Java-8 - to write a logic. My colleagues can't understand it. Try it!

##Foreword
I wrote a paragraph of logic in Java 8, but my colleagues said they couldn't understand it. The following is the business background. You can have a look together!

Business background

First of all, the business needs are as follows: pull all orders from the third-party e-commerce platform and save them to the company's own database. You need to judge whether there is logistics information. If there is logistics information, you need to upload it again.

The data returned by the third-party interface is in JSON format, but the logistics information is very deep, as shown below. The JSON node is as follows:

xxxOrder > xxxShippingInfo > xxxShipmentDetails > xxxTrackingInfo > trackingNumber, trackingLink

Basic implementation

Because the data returned by the third-party interface is in JSON format, you need to convert the JSON string into a Java object for processing.

@JsonIgnoreProperties(ignoreUnknown = true)
public class XxxOrder {

    /**
     * Logistics information
     */
    @JsonProperty("shippingInfo")
    private XxxShippingInfo xxxShippingInfo;

}

The above is only the first layer example. To get the logistics information, you need to encapsulate four layers of objects in turn. To avoid null pointers when really obtaining the logistics information, you need to judge 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){
				...
			}
		}
	}
}

It's so troublesome to get a logistics information. I'm also drunk. It's not elegant to write like this.

Java 8 implementation

Because I know that Java 8 can handle such needs, I never thought of implementing it in the most primitive way. I directly implemented it in Java 8:

/**
* 
/
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 writing, my colleagues shouted that they couldn't understand it and came to me to ask me..

Implementation principle

In fact, this does not use any superb technology. It is implemented by using java 8 option. I won't introduce the details. It is mainly to avoid null pointers. You can click if you don't understand here View this article.

Today, let's introduce the principle of the Optional#map method to realize this logic. Let's look at the source code of the map implementation:

public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
    // Functional interface cannot be null
    Objects.requireNonNull(mapper);

    // If there is no current value, an empty option is returned
    if (!isPresent())
        return empty();
    else {
        // If there is currently a value, return a result of functional processing of the value Optional
        return Optional.ofNullable(mapper.apply(value));
    }
}

// Determine whether the Optional Value has a value
public boolean isPresent() {
    return value != null;
}

// Create an Optional, which can be empty
public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}

So back to this procedure:

// If the root object is empty, create an empty option; otherwise, create an option of the root object
Optional.ofNullable(xxxOrder)
    // If the root object is null, it will directly return null Optional; otherwise, it will return Optional of this value
    .map((o) -> o.getXxxShippingInfo())
    // And so on
    .map((si) -> si.getXxxShipmentDetails())
    .map((sd) -> sd.getXxxTrackingInfo())
    .map((t) -> new String[]{t.getTrackingNumber(), t.getTrackingLink()})
    // null is returned if the value cannot be obtained
    .orElse(null);
}

Maybe you still don't understand it after reading it. I admit, it's really around and it's not easy to understand. This can only be meaningful and unspeakable. You can understand it with more reading and practice.

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

The program is used xx. xx. For chain calls such as XX, the map method must be Optional, and the return result of the map is Optional.

One question is, if they are all empty, will not all map s go through? Will performance be affected in this case? Will the compiler optimize? This is unknown for the time being.

In addition, there is also a "flatMap" method. What is the difference between "flatMap" and "flatMap"?

The returned result of flatMap # needs to encapsulate the Optional return in the functional interface, which is not suitable for application here.

summary

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

In fact, I personally have been working hard to learn this knowledge. I have learned the latest Java 14 and have shared a series of new feature articles before,

Therefore, although I am an old front wave now, I feel that I have come to the front of many back waves in learning and mastering new knowledge.
##Finally
After reading, you can leave a message below to discuss what you don't understand
Thank you for watching.
If you think the article is helpful to you, remember to pay attention to me and give me some praise and support!

Original link: Java technology stack

summary

For the interview, we must have a good attitude. When this little partner interviewed meituan, he was not affected by Ali's interview in front. He played normally and could successfully win meituan's offer.
Xiaobian also sorted out most of the interview questions and answers involved in the interview of java programmers in large factories. I hope I can help you. If you need it, you can see the following free collection method!

↓↓↓
Click here to download for free

Click here to download for free

[external chain picture transferring... (img-UauJpjSy-1623620446846)]

[external chain picture transferring... (img-VYH2o4Dx-1623620446847)]

Finally, thank you for your support. I hope the materials compiled by Xiaobian can help you! I also wish everyone a promotion and a raise!

Keywords: Java Interview Programmer

Added by forumsudhir on Mon, 31 Jan 2022 20:01:00 +0200