首页 > 编程语言 > 详细

Java8 中的 Optional 相关用法

时间:2019-05-11 11:13:53      阅读:318      评论:0      收藏:0      [点我收藏+]

基本方法:

  • of() 为非 null 的值创建一个 Optional 实例
  • isPresent() 如果值存在,返回 true,否则返回 false
  • get() 返回该对象,有可能返回 null

 

应用场景:

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

Java8 中的 Optional 相关用法

原文:https://www.cnblogs.com/lemos/p/10847523.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!