Java8 中的 Optional 相關用法
阿新 • • 發佈:2019-05-11
getch mil div vertical mod set padding 傳統 uri
基本方法:
of()
為非 null 的值創建一個 Optional 實例isPresent()
如果值存在,返回 true,否則返回 falseget()
返回該對象,有可能返回 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 相關用法