Optional.ofNullable()替换if判断是为空

if写法:

if(ObjectUtil.isNotEmpty(o.getInStockUerId())){
                    o.setInStockUerName(UserCache.getUser(o.getInStockUerId()).getRealName());
}
替换:Optional.ofNullable写法
String inUserName = Optional.ofNullable(UserCache.getUser(o.getInStockUerId())).orElse(new User()).getRealName();
o.setInStockUerName(inUserName);

 点击查看源码:为空返回空的Optional

 /**
     * Common instance for {@code empty()}.
     */
    private static final Optional EMPTY = new Optional<>();

 /**
     * Returns an {@code Optional} describing the specified value, if non-null,
     * otherwise returns an empty {@code Optional}.
     *
     * @param  the class of the value
     * @param value the possibly-null value to describe
     * @return an {@code Optional} with a present value if the specified value
     * is non-null, otherwise an empty {@code Optional}
     */
    public static  Optional ofNullable(T value) {
        return value == null ? empty() : of(value);
    }


/**
     * Returns an empty {@code Optional} instance.  No value is present for this
     * Optional.
     *
     * @apiNote Though it may be tempting to do so, avoid testing if an object
     * is empty by comparing with {@code ==} against instances returned by
     * {@code Option.empty()}. There is no guarantee that it is a singleton.
     * Instead, use {@link #isPresent()}.
     *
     * @param  Type of the non-existent value
     * @return an empty {@code Optional}
     */
    public static Optional empty() {
        @SuppressWarnings("unchecked")
        Optional t = (Optional) EMPTY;
        return t;
    }

/**
     * Returns an {@code Optional} with the specified present non-null value.
     *
     * @param  the class of the value
     * @param value the value to be present, which must be non-null
     * @return an {@code Optional} with the value present
     * @throws NullPointerException if value is null
     */
    public static  Optional of(T value) {
        return new Optional<>(value);
    }
 
  

你可能感兴趣的:(java)