Java8 Optional 作用与实例
Java 8 Optional 类
Optional 着重为解决 java 的 NPE 问题是 Java8 提供的为了解决 null 安全问题的一个 API。善用 Optional 可以使我们代码中很多繁琐、丑陋的设计变得十分优雅。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| 使用Optional,我们就可以把下面这样的代码进行改写: 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; }
这样才是正确使用Optional的姿势。那么按照这种思路,我们可以安心的进行链式调用,而不是一层层判断了。 public static String getName(User u) { return Optional.ofNullable(u) .map(user->user.name) .orElse("Unknown"); }
看一段代码: 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."); }
让我们看看经过Optional加持过后,这些代码会变成什么样子。 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.")); }
还有很多不错的使用姿势,比如为空则不打印可以这么写: string.ifPresent(System.out::println);
|
若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏