publicstatic 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(); } } } thrownew IllegalArgumentException("The value of param comp isn't available."); }
改造后:
1 2 3 4 5 6 7
publicstatic 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.")); }
使用Optional 可以配合 Stream 实现更优雅的写法。
二、Optional API 介绍
1 2 3 4 5 6 7 8
/** * Common instance for {@code empty()}. */ privatestaticfinal Optional<?> EMPTY = new Optional<>(); /** * If non-null, the value; if null, indicates no value is present */ privatefinal T value;
构造函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * Constructs an empty instance. * @implNote Generally only one empty instance, {@link Optional#EMPTY}, * should exist per VM. */ privateOptional(){ this.value = null; }
/** * Constructs an instance with the value present. * @param value the non-null value to be present * @throws NullPointerException if value is null */ privateOptional(T value){ this.value = Objects.requireNonNull(value); }
// 和 Stream 中一样的用法 public Optional<T> filter(Predicate<? super T> predicate){...} public<U> Optional<U> map(Function<? super T, ? extends U> mapper){...} public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper){...}
// 容器的值 == null,返回 other、否则返回 value public T orElse(T other){ return value != null ? value : other; } // 同上面类似 public T orElseGet(Supplier<? extends T> other){ return value != null ? value : other.get(); } // 同上, 会抛出异常 public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)throws X {...}
for (String name : names) { Optional<String> optional = Optional.ofNullable(name) .filter(value -> value.length() > 7); System.out.println(optional.orElse("less than 7 characters")); } // result zhuxiaoming wangdachui less than 7 characters