Optional类(不讲废话)

1.创建Optional对象方式

1.1 Optional.of(T value)

User orginalUser1 = new User("1", "user1");
Optional<User> user1 = Optional.of(orginalUser1);
复制代码

说明: Optional只能接受非null的对象,源码追踪如下

...
public static <T> Optional<T> of(T value) {
    return new Optional<>(value);
}
...
private Optional(T value) {
    this.value = Objects.requireNonNull(value);
}
...
public static <T> T requireNonNull(T obj) {
    if (obj == null)
        throw new NullPointerException();
    return obj;
}
复制代码

1.2 Optional.ofNullable(T value)

User orginalUser2 = null;
Optional<User> user2 = Optional.ofNullable(orginalUser2);
复制代码

说明: 与.of方法不同的是ofNullable可以接受null值,null值返回Empty(); 源码追踪如下

...
public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}
...
public static<T> Optional<T> empty() {
    @SuppressWarnings("unchecked")
    Optional<T> t = (Optional<T>) EMPTY;
    return t;
}
复制代码

小结:通常我们尽可能的使用.ofNullable方法

2.方法API

*Present系列

isPresent() 判断当前对象是否不为空

示例

if (user1.isPresent()) {
    System.out.println(user1);
}
复制代码

源码

public boolean isPresent() {
    return value != null;
}
复制代码

说明 无

ifPresent(Consumer<? super T> consumer) 不为空对他做些什么

示例

user1.ifPresent(System.out::println);
复制代码

源码

public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
    consumer.accept(value);
}
复制代码

说明 无

orElse*系列

orElse(T other) 不为空就返回自身,空就返回other值

示例

User user = user1.orElse(new User("999", "999A"));
复制代码

源码

public T orElse(T other) {
    return value != null ? value : other;
}
复制代码

orElseGet(Supplier<? extends T> other) 不为空就返回自身,空就根据传入的函数返回对应的值

示例

User orElseGet = user1.orElseGet(() -> new User("orElseGet","orElseGet"));
复制代码

源码

public T orElseGet(Supplier<? extends T> other) {
    return value != null ? value : other.get();
}

复制代码

orElseThrow(Supplier<? extends X> exceptionSupplier) 空的话就抛出异常

示例

user1.orElseThrow(() -> new Exception("user对象不能为空!"))
复制代码

源码

public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
    if (value != null) {
        return value;
    } else {
        throw exceptionSupplier.get();
    }
}
复制代码

*map系列

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

示例

List<String> orderList1 = user1.map(u -> u.getOrders()).orElse(Collections.emptyList());
复制代码

源码

public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent())
        return empty();
    else {
        return Optional.ofNullable(mapper.apply(value));
    }
}
复制代码

说明 map接受的入参是Function<? super T, ? extends U>

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

示例

// User类中flatName类型如下
private String flatMapName;
public Optional<String> getFlatMapName() {
    return Optional.ofNullable(flatMapName);
}
...
String flatName = user1.flatMap(User::getFlatMapName).orElse(null);
复制代码

源码

public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent())
        return empty();
    else {
        return Objects.requireNonNull(mapper.apply(value));
    }
}
复制代码

说明 flatMap接受的入参是Function<? super T, Optional>

filter(Predicate<? super T> predicate) 过滤用的

示例

Optional<User> user = user1.filter(u -> u.getName().length() > 6);
复制代码

源码

public Optional<T> filter(Predicate<? super T> predicate) {
    Objects.requireNonNull(predicate);
    if (!isPresent())
        return this;
    else
        return predicate.test(value) ? this : empty();
}
复制代码

最后示例

获取用户地址里面的城市下的cityCody

// 原写法
public static String getCityCode(User user) throws Exception {
    if (null != user.getAddress()) {
        if (null != user.getAddress().getCity()) {
            return user.getAddress().getCity().getCityCode();
        }
    }
    throw new Exception("获取cityCode失败");
}
// Optional简化
public static String getCityCode2(User user) throws Exception {
    Optional<User> optionalUser = Optional.ofNullable(user);
    return optionalUser.map(item -> item.getAddress()).map(o -> o.getCity()).map(o -> o.getCityCode()).orElseThrow(() -> new Exception("获取cityCode失败"));
}
复制代码

对象非空TODO sth

// 原写法
if (null!=user) {
    // TODO sth
}
// Optional简化
optionalUser.ifPresent(o -> {
    // TODO sth
});
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值