Java8 中的 Optional 相关用法

基本方法:

  • ofNullable() 为可能 null 的值创建一个 Optional 实例,  然后可以对该实例遍历/过滤, 判断是否存在,或者为空时执行..
  • ifPresent(...) 如果值存在则执行里面的方法

 

应用场景:

1> 默认值

传统方式

public static String getName(User u) {
    if (u == null)
        return "Unknown";
    return u.name;
}

杜绝使用这种方式(不简洁)

public static String getName(User u) {
    Optional<User> user = Optional.ofNullable(u);
    if (!user.isPresent())
        return "Unknown";
    return user.get().name;
}

正确方式(链式调用):

public static String getName(User u) {
    return Optional.ofNullable(u)
                    .map(user->user.name)
                    .orElse("Unknown");
      //.orElseGet(() -> "john");
}

 

2>多重非空条件判断

传统方式

public static String getChampionName(Competition comp) throws IllegalArgumentException {
    if (comp != null) {
        CompResult result = comp.getResult();
        if (result != null) {
            User champion = result.getChampion();
            if (champion != null) {
                return champion.getName();
            }
        }
    }
    throw new IllegalArgumentException("The value of param comp isn't available.");
}

链式调用(map 遍历属性)

public static String getChampionName(Competition comp) throws IllegalArgumentException {
    return Optional.ofNullable(comp)
            .map(c->c.getResult())
            .map(r->r.getChampion())
            .map(u->u.getName())
            .orElseThrow(()->new IllegalArgumentException("The value of param comp isn't available."));
}

  

 3> 不为空才操作(单边判断)

string.ifPresent(System.out::println);

 

4> 指定条件过滤

public boolean priceIsInRange2(Modem modem2) {
     return Optional.ofNullable(modem2)
       .map(Modem::getPrice)
       .filter(p -> p >= 10)
       .isPresent();
 }

 

5. filter 与 findFirst 结合

Optional<String> found = Stream.of(getEmpty(), getHello(), getBye())
      .filter(Optional::isPresent)
      .map(Optional::get)
      .findFirst();

 

 

233

转载于:https://www.cnblogs.com/lemos/p/10847523.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值