先介紹一下API,與其他文章不同的是,本文采取類比的方式來講,同時結合源碼。而不像其他文章一樣,一個個API羅列出來,讓人找不到重點。
1、Optional(T value),empty(),of(T value),ofNullable(T value)
這四個函數之間具有相關性,因此放在一組進行記憶。
先說明一下,Optional(T value),即構造函數,它是private權限的,不能由外部調用的。其余三個函數是public權限,供我們所調用。那么,Optional的本質,就是內部儲存了一個真實的值,在構造的時候,就直接判斷其值是否為空。好吧,這么說還是比較抽象。直接上Optional(T value)構造函數的源碼,如下圖所示

方式一:
1 public static void implement(User user) throws Exception { 2 // 原始 ---> 01 3 before01(user); 4 // 優化 ---> 01 5 upgrade01(user); 6 } 7 8 public static String before01(User user) throws Exception { 9 // if(user!=null){ 10 // if(user.getAddress()!=null){ 11 // Address address = user.getAddress(); 12 // if(address.getName()!=null){ 13 // return address.getName(); 14 // } 15 // } 16 // } 17 // throw new Exception("取值錯誤"); 18 if (null != user && null != user.getAddress() && null != user.getAddress().getName()) { 19 return user.getAddress().getName(); 20 } 21 throw new Exception("取值錯誤"); 22 } 23 24 public static String upgrade01(User user) throws Exception { 25 return Optional.ofNullable(user) 26 .map(user1 -> user1.getAddress()) 27 .map(user2 -> user2.getName()) 28 .orElseThrow(() -> new Exception("取值錯誤")); 29 }
方式二:
1 public static void before02(User user){ 2 if (null != user){ 3 test(); 4 } 5 } 6 7 public static void upgrade02(User user){ 8 Optional.ofNullable(user).ifPresent(user1 -> test()); 9 }
方式三:
1 public static User before03(User user) throws Exception{ 2 if(user!=null){ 3 String name = user.getName(); 4 if("King".equals(name)){ 5 return user; 6 } 7 }else{ 8 user = new User(); 9 user.setName("King"); 10 return user; 11 } 12 throw new Exception("取值錯誤"); 13 } 14 15 public static void upgrade03(User user){ 16 Optional.ofNullable(user) 17 .filter(user1 -> "King".equals(user.getName())) 18 .orElseGet(() -> { 19 User user2 = new User(); 20 user2.setName("King"); 21 return user2; 22 }); 23 }
轉載地址:https://blog.csdn.net/wmq880204/article/details/112659166
