[JAVA basics] Optional class

Optional is a nullable container object. If the value exists, the isPresent() method will return true, and the get() method will return the object. Can avoid null pointer exception

Common method:

serial number Method & Description
1 static <T> Optional<T> empty()

Returns an empty Optional instance.

2 boolean equals(Object obj)

Determines whether other objects are equal to Optional.

3 Optional<T> filter(Predicate<? super <T> predicate)

If the value exists and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.

4 <U> Optional<U> flatMap(Function<? super T,Optional<U>> mapper)

Returns the value based on the mapping method contained in the Optional if the value exists, otherwise returns an empty Optional

5 T get()

If this value is included in this Optional, return the value, otherwise throw an exception: NoSuchElementException

6 int hashCode()

Returns the hash code of the value that exists, or 0 if the value does not exist.

7 void ifPresent(Consumer<? super T> consumer)

If the value exists then call the consumer with that value, otherwise do nothing.

8 boolean isPresent()

The method returns true if the value exists, false otherwise.

9 <U>Optional<U> map(Function<? super T,? extends U> mapper)

If the value exists, the provided mapping method, if non-null, returns an Optional describing the result.

10 static <T> Optional<T> of(T value)

Returns an Optional specifying a non-null value.

11 static <T> Optional<T> ofNullable(T value)

Returns the specified value described by Optional if non-null, otherwise returns an empty Optional.

12 T orElse(T other)

Returns the value if the value exists, otherwise returns other.

13 T orElseGet(Supplier<? extends T> other)

Returns the value if the value exists, otherwise fires other and returns the result of the call to other.

14 <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)

If the value exists, return the contained value, otherwise throw the exception inherited by Supplier

15 String toString()

Returns an Optional non-empty string for debugging

Note: These methods are inherited from the java.lang.Object class.

Example 1: List

 @Test
    public void test(){
        Optional<Employee> optional = Optional.of(null);
        Employee employee = optional.get();//of获取实例

        optional  = Optional.empty();//没有值创建一个空的optional
        System.out.println(optional.get());

        optional = Optional.ofNullable(null);//若参数不为null,创建实例,否则创建空实例
        optional = optional.ofNullable(new Employee("张三",19,999.99, Employee.Status.FREE));
        Optional<String> stringOptional = optional.flatMap((e)->Optional.of(e.getName()));//返回值必须是Optional
        stringOptional = optional.map((e)->e.getName());//如果有值对其处理返回处理结果,否则返回Optional.empty()

        //有值返回:new的实例也算有值,没有值 返回参数
        Employee employee1 = optional.orElse(new Employee("张三",19,999.99, Employee.Status.FREE));

        if(optional.isPresent()){//有值获取,没值什么都不做
            System.out.println(optional.get());
        }

        Employee employee2 = optional.orElseGet(()->new Employee());//有值返回,没有值返回Supplier参数获取的值

    }

Example two:

@Test
    public void testForUse(){
        Man man = new Man();
        String n = getGodnessName(man);

        Optional<Godness> godness = Optional.ofNullable(new Godness("华晨宇"));//若参数不为null,创建实例,否则创建空实例
        Optional<NewMan> newMan = Optional.ofNullable(new NewMan(godness));
        String str = getGodnessName2(newMan);
    }

    public String getGodnessName2(Optional<NewMan> man){//optional包装
        return man.orElse(new NewMan())//有则用,没有用参数
                .getGodness()
                .orElse(new Godness("水货、跑路"))
                .getName();
    }

    public String getGodnessName(Man man){//手动判null
        if(man != null){
            Godness gn = man.getGodness();
            if(gn != null){
                return gn.getName();
            }
        }
        return "天才";
    }

A rookie tutorial:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325548667&siteId=291194637