Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

The new Java8 feature includes stream-related operations, which are easy to use in projects because of streaming programming. However, if there is a possibility that the intermediate result object will be null during the streaming operation, the null pointer exception will be reported during the streaming operation.

1. NullPointerException

A NullPointerException is a runtime exception that occurs when a property or method call is made to a null object, causing the program to run abnormally.

In the business processing of project development, the most common exception is null-pointer exception. Proper handling of null-pointer exception can make the project more stable.

This article focuses on gracefully handling nullpointerexceptions in Java8 streaming operations.

2. Handle NullPointerException in Java8

Existing business scenarios include Order and Product classes: Order and Product, whose relationship is shown as follows:

public class Production {
    private Integer productionId;
    private String productName;
    private ProductSpecification productSpec;
}

public class ProductSpecification {
    private Integer productSpecId;
    private String productSpecName;
}
Copy the code

2.1 service logic processing before Java8

If we need to get information about a specified item from an order, we need to have an action:

// The judgment condition is complex
public String getSpecName(Product product) {
    if(product ! =null&& product.getSpec ! =null) {
            return product.getSpec.getSpecName();
    }else {
        return ""; }}// The logic is bloated
public String getSpecName(Product product) {
    if(product ! =null) {
            Specification spec = product.getSpec;
            if(spec ! =null) {
                return spec.getSpecName();
            } else {
                    return ""; }}else {
        return ""; }}Copy the code

It can be seen that when we operate on an object, we need to perform nullifying operation on the object involved in the operation process, a large number of nullifying operations and if.. Else leads to very bloated code.

2.2 Java8 operation

For frequent nullation and code bloatiness, we can use Java8’s Stream operation to implement object values.

public void print(Product product){
    Optional.ofNullable(production)
            .map(Production::getProductSpec)
            .ifPresent(specInfo -> System.out.println(specInfo.getSpecName()));
}
Copy the code

The logic of this code can be understood as follows:

  1. If production is null, an empty Optional object is returned with no output value
  2. If production is not null, the productSpec property in production is obtained through the getProductSpec method
  3. If the productSpec attribute exists, output its productSpecName value.

2.3 Optional

Optional is a new Java8 container that contains one or zero elements. Optional is used to prevent nullPointExceptions. Common methods are:

  • Option.empty () : Creates an empty Optional instance
  • Option. of(T T) : Creates an Optional instance that reports exceptions for null
  • Option. ofNullable(T T): If T is not null, create an Optional instance; otherwise, create an empty instance
  • IsPresent () : Checks if there is a value in the container
  • IfPresent (Consume lambda) : Execute the lambda expression in parentheses if the container is not empty
  • OrElse (T T) : Gets the elements in the container, or returns the default values in parentheses if the container is empty
  • OrElseGet (Supplier s) : Returns the value if the calling object contains it, otherwise returns the value obtained by S
  • Map (Function f): if it has a value, return the processed Optional, otherwise return option.empty ()
  • FlatMap (Function mapper): Similar to map, the return value must be Optional
  • T get() : Gets elements from the container, and raises NoSuchElement if the container is empty

3. Summary

Java8 streaming operation adds a lot of convenience, but nullpointerexceptions still exist when ordinary streaming operation is used. Therefore, more consideration should be given to the business processing logic of actual projects to reduce the impact of exceptions on system stability.

Optional is a new method for gracefully handling NullPointerExceptions. It provides a number of methods for nullPointerExceptions and is suitable for object manipulation.

This article is intended as an Optional introduction to learning and a key to unlocking a new door for further study in the days to come.

Java is 16, Java8 still fast master!