Java Optional Class

One, background

1. Optional principal null pointer exception solve the problems and avoid the explicit determination null pointer, checking to reduce defensive null

2. draws on google guava class of Optional

3. Optinal class has a field value, whether the primary value is to be Null operations and judgments

 

Second, Optional create an instance of the class, a construction method, a static method 3

1. Constructors private Optional (T value), because it is private and can not be accessed externally, it can not call the constructor to create an object, null pointer exception will be reported

    private Optional(T value) {
        this.value = Objects.requireNonNull(value);
    }

2. of () static method, the underlying calls the private constructor, still will be reported null pointer exception

public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}

Optional<String> optStr1 = Optional.of("optional");

3. empty () static method, not reported null pointer, returns a null value Optional objects

public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}

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

4. ofNullable () static method call to the underlying empty () and of () method, if the incoming value is null, it returns null value Optional objects, otherwise the return value is not null as the Optional recommended

public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}

Optional<String> optStr2 = Optional.ofNullable(null);

 

Three, Optional use

1. get () method, used with caution, returns the wrapped object actual value, null will throw an exception NoSuchElementException

 

2.isPresent() vs ifPresent()

isPresent () method, used with caution, determining whether the actual value of the wrapped object nonempty

The IfPresent () method, a Consumer receiving object if the value is not null, the object execution Consumer accept () method (a parameter has no return value)

Note: Do not write, because the judge still null, with no difference without using the Optional

User user = Optional.ofNullable(user);
if (Optional.isPresent()){
   // TODO: do something
}

 

3. filter () method, a receiving Predicate object, i.e., a determination condition for Optional filter object

Optional<User> user1 = Optional.ofNullable(user).filter(u -> u.getName().length()<6);

 

4. map () vs flatMap () value conversion for

map () method, a receiving Function <? super T,? extends U> object, the function is calculated by Function

flatMap () method for receiving a Function <? super T, Optional <U >> objects, calculated by Function Function

 

5. orelse () vs orElseGet () vs orElseThrow ()

orElse () method, the value is null, the default value is returned; even if the value is not null, still performs orElse (), is not recommended

orElseGet () method, a Supplier receiving object () method is used as the default value Supplier get object, when the value is not null, not execute orElseGet (), is recommended

orElseThrow () method, a receiving Supplier objects, an object must return an exception Supplier

 

4, the actual scene

1. 

public String getCity(User user)  throws Exception{
        if(user!=null){
            if(user.getAddress()!=null){
                Address address = user.getAddress();
                if(address.getCity()!=null){
                    return address.getCity();
                }
            }
        }
        throw new Excpetion("取值错误"); 
}

public String getCity(User user) throws Exception{
    return Optional.ofNullable(user)
                   .map(u-> u.getAddress())
                   .map(a->a.getCity())
                   .orElseThrow(()->new Exception("取指错误"));
}

 

2. 

if(user!=null){
    dosomething(user);
}

Optional.ofNullable(user)
         .ifPresent(u->{
            dosomething(u);
});

 

3. 

public User getUser(User user) throws Exception{
    if(user!=null){
        String name = user.getName();
        if("zhangsan".equals(name)){
            return user;
        }
    }else{
        user = new User();
        user.setName("zhangsan");
        return user;
    }
}

public User getUser(User user) {
    return Optional.ofNullable(user)
                   .filter(u->"zhangsan".equals(u.getName()))
                   .orElseGet(()-> {
                        User user1 = new User();
                        user1.setName("zhangsan");
                        return user1;
                   });
}

 

 

 

 

reference: 

https://www.jianshu.com/p/d81a5f7c9c4e

https://www.cnblogs.com/rjzheng/p/9163246.html

 

Guess you like

Origin www.cnblogs.com/june0816/p/11442923.html