Java Optional

 

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

解决空值问题,避免显式检查null。

        String s;

        //prior java 8
        if(s==null){
            length=0;
        }else {
            length=s.length();
        }

        //java8
        int length = Optional.of(s)
                .map(o -> o.length())
                .orElse(0);

orElse & orElseGet

orElse(T other)

Return the value if present, otherwise return other

orElseGet(Supplier<? extends T> other)

Return the value if present, otherwise invoke other and return the result of that invocation.

如果Optional的值不存在的话,orElse 返回一个值(T ohter),orElseGet调用一个Supplier产生一个值(T other)

区别在于,orElseGet中的supplier是懒加载的,只有在Optional的值不存在的时候,才会调用并产生值ohter。

如果错误的使用orElse(Supplier<? extends T> other),那么该supplier一定会执行(无论Optional的值是否存在)

https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

posted @ 2018-07-28 23:54  SEC.VIP_网络安全服务  阅读(74)  评论(0编辑  收藏  举报