One Java8 new features: Optional Class

Optional keyword null is not a substitute for, but rather for null judgment provides a more elegant implementation

NullPointException can be said that all the java developers encountered an exception, though java from initial design to programmers trying to get out of Oliver pointer, but the pointer is indeed real, and java designer can only make pointer become more simple, easy to use, but can not be completely removed, so only the keywords we have seen in the daily java language null.

Null pointer exception is a runtime exception, for this type of exception if there is no clear treatment strategy, the best practice is to allow the program to hang early, but in many scenes, not the developer is no specific treatment strategy, but simply not aware of the existence of a null pointer exception. When an exception does occur, the treatment strategy is simple, add an if statement to determine where there are unusual, but such coping strategies make our program more and more null judgment, we know a good programming, code should be allowed to try to appear less null keyword, java8 offered Optionalclasses at reducing NullPointException, but also enhance the appearance of the code. But first we need to be clear that it  is not for nullan alternative keywords, but for null judgment provides a more elegant implementation, thus avoiding NullPointException .

A. Intuitive feelings

Suppose we need to return the length of a string, if you do not use third-party tools, we need to call the str.length()method:

if (null == str) {// null pointer is determined 
    return 0; 
} 
return str.length ();

Optional If the class, implemented as follows:

return Optional.ofNullable(str).map(String::length).orElse(0);

Optional relatively more concise code, when the code is large, it is easy to forget to null judgment, but the use of Optional classes will avoid such problems.

II. Basic use

1. Object Creation

Create a null object

Optional<String> optStr = Optional.empty();

The above example code calls the empty()method creates an empty Optional<String>Object type.

Create objects: NOT NULL
provides a method Optional of()non-null object used to create, this method requires the incoming parameters can not be empty, otherwise throw NullPointException, examples are as follows:

Optional <String> optStr = Optional.of (str); // if str is null when thrown NullPointException

Create Object: allowed to be null
if the incoming parameters can not be determined whether the possibility of the presence of a null value, you can use the Optional ofNullable()create an object method, if the parameter is null, a null object is created. Examples are as follows:

Optional <String> optStr = Optional.ofNullable (str); // If str is null, then create an empty object

2. Streaming

Streaming is java8 brought us a heavyweight new feature, let's set of operations to become more concise and efficient, the next article on java8 new features, will deal with the loss of a full explanation. Here Optional also provides two basic loss treatment: mapping and filtering.

To demonstrate, we have designed a Userclass, as follows:

/**
 * @author: zhenchao.Wang 2016-9-24 15:36:56
 */
public class User {

    /** 用户编号 */
    private long id;

    private String name;

    private int age;

    private Optional<Long> phone;

    private Optional<String> email;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 省略setter和getter
}

Phone and E-mail is not a man to be there, so we use Optional definition.

Map: map and flatMap
mapping operation to convert an input into another form of output, such as the previous example, we have the input string, and the output is the length of the string, this is a hint, the method we use map()to achieve. Suppose we want to get a person's name, then we can achieve the following:

String name = Optional.ofNullable(user).map(User::getName).orElse("no name");

So that when the user parameter is not empty when its name is returned, otherwise no name , as I hope we get phone or email through the above way, the way of using the above does not work, because the return after the map is Optional, we call this Optional called nesting, we must once in order to get the results we want in the map:

long phone = optUser.map(User::getPhone).map(Optional::get).orElse(-1L);

In fact, this time, a better way is to use flatMap, step to get the results we want:

long phone = optUser.flatMap(User::getPhone).orElse(-1L);

flapMap each stream may be returned by the method flattened into a stream, particularly a lower devoted streamed article elaborate.

Filter: Fliter
filiter, as the name suggests is a filter operation, we can pass the filtration operation as a parameter to the method, in order to achieve the purpose of filtering, we want to filter was added over 18 adults, can be achieved as follows:

optUser.filter(u -> u.getAge() >= 18).ifPresent(u -> System.out.println("Adult:" + u));

3. The default behavior

The default behavior is when the operation Optional condition is not satisfied performed, for example, in the above example we use orElse()is a default action for Optional object to perform a specific action is empty, of course, there are some default action when the condition the operation performed in the presence of an object.

GET ()
GET used to obtain the value of a variable, but when the variable does not exist will be thrown NoSuchElementException, so not sure if the variable exists, use is not recommended

orElse (T other)
when Optional variable satisfies the predetermined condition, orElse is performed, such as when the front str is null, 0 is returned.

orElseGet (<? extends X> Supplier expectionSupplier)
If the conditions are not established, you need to perform relatively complex logic, rather than simply return to operation, you can use orElseGet achieved:

long phone = optUser.map(User::getPhone).map(Optional::get).orElseGet(() -> {
    // do something here
    return -1L;
});

orElseThrow (Supplier <? extends X> expectionSupplier)
similar to the get () method returns an exception when all conditions are not satisfied, but here we can specify the type of exception returned.

ifPresent (Consumer <? super T> )
performed operation parameter passed when the condition is satisfied.

III. Precautions

Optional is a final class does not implement any interface, so when we use attribute class packaging class definition, if we define the classes have serialization needs, so as not implement Serializable interface Optional, this time to perform serialization operation will be a problem:

the User class the implements the Serializable {public 

    / user number ** * / 
    Private Long ID; 

    Private String name; 

    Private int Age; 

    Private Optional The <Long> Phone; // can not be serialized 

    private Optional <String> email; // can not be serialized

But we can use the following replacement policy:

private long phone;

public Optional<Long> getPhone() {
    return Optional.ofNullable(this.phone);
}

It seems Optional when the design did not consider it to be used as a kind of field -

Published an original article · won praise 1 · views 71

Guess you like

Origin blog.csdn.net/f_u_c_k_le/article/details/105278616