<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # Java 8 `Optional`類 > 原文: [https://beginnersbook.com/2017/10/java-8-optional-class/](https://beginnersbook.com/2017/10/java-8-optional-class/) 在 Java 8 中,我們在`java.util`包中新引入了`Optional`類。引入此類是為了避免在我們的代碼中不執行空檢查時經常遇到的`NullPointerException`。使用這個類,我們可以很容易地檢查變量是否具有`null`值,通過這樣做,我們可以避免`NullPointerException`。在本指南中,我們將了解如何使用`Optional`類以及此類的各種方法的用法。 在我們看到`Optional`類的示例之前,讓我們看看當我們不使用`Optional`類并且不執行`null`檢查時會發生什么。 ## Java 示例:不使用`Optional`類 在這個例子中,我們沒有將值賦給`String str`,我們試圖從中獲取[子串](https://beginnersbook.com/2013/12/java-string-substring-method-example/)。由于`str`中沒有值,程序拋出`NullPointerException`。 ```java public class Example { public static void main(String[] args) { String[] str = new String[10]; //Getting the substring String str2 = str[9].substring(2, 5); //Displaying substring System.out.print(str2); } } ``` 輸出: ```java Exception in thread "main" java.lang.NullPointerException at Example.main(Example.java:5) ``` ## 解決方案:使用`Optional`類 `Optional`類的`Optional.ofNullable()`方法,如果給定對象有值,則返回非空`Optional`,否則返回空`Optional`。 我們可以使用`isPresent()`方法檢查返回的`Optional`值是空還是非空。 ```java //Importing Optional class import java.util.Optional;? public class Example {? public static void main(String[] args) {??? ? String[] str = new String[10];??? ? Optional<String> isNull = Optional.ofNullable(str[9]);??? ? ? ? if(isNull.isPresent()){? ? ? ?//Getting the substring?? ? ? ? ? ?String str2 = str[9].substring(2, 5);? ? ? ? ? ?//Displaying substring? ? ? ? ? ? System.out.print("Substring is: "+ str2);?? ? ? ? }? ? ? ? else{? ? ? ? System.out.println("Cannot get the substring from an empty string");? ? ? ? }? ? ? ? ?? ? ? ? str[9] = "AgraIsCool";? ? ? ? Optional<String> isNull2 = Optional.ofNullable(str[9]);?? ? ? ? if(isNull2.isPresent()){? ? ? ? ?//Getting the substring?? ? ? ? ? ? String str2 = str[9].substring(2, 5);? ? ? ? ? ? //Displaying substring? ? ? ? ? ? System.out.print("Substring is: "+ str2);?? ? ? ? ? }? ? ? ? ? else{? ? ? ? ? System.out.println("Cannot get the substring from an empty string");? ? ? ? ? }? ? }?? } ``` 輸出: ```java Cannot get the substring from an empty string Substring is: raI ``` ## 示例:`Optional`的`isPresent()`和`ifPresent()`方法 在上面的例子中,我們已經看到通過使用`isPresent()`方法,我們可以檢查特定的`Optional`對象(或實例)是空還是非空。 `Optional`類中還有另一種方法,只有在給定的`Optional`對象為非空時才執行,方法為`ifPresent()`。讓我們看一個例子來理解差異。 ```java //Importing Optional class import java.util.Optional; ? public class Example {?? public static void main(String[] args) { //Creating Optional object from a String Optional<String> GOT = Optional.of("Game of Thrones");? ? ? ? //Optional.empty() creates an empty Optional object? ? ? ? Optional<String> nothing = Optional.empty(); /* isPresent() method: Checks whether the given Optional? ? ? ? ? * Object is empty or not.? ? ? ? ? */? ? ? ? if (GOT.isPresent()) {? ? ? ? ? ? System.out.println("Watching Game of Thrones");? ? ? ? } else {? ? ? ? ? ? System.out.println("I am getting Bored");? ? ? ? } /* ifPresent() method: It executes only if the given Optional? ? ? ? ? * object is non-empty.? ? ? ? ? */? ? ? ? //This will print as the GOT is non-empty? ? ? ? GOT.ifPresent(s -> System.out.println("Watching GOT is fun!"));? ? ? ??? ? ? ? //This will not print as the nothing is empty? ? ? ? nothing.ifPresent(s -> System.out.println("I prefer getting bored")); } } ``` 輸出: ```java Watching Game of Thrones Watching GOT is fun! ``` ## Java 8 - `Optional`的`orElse()`和`orElseGet()`方法 如果該對象為空,則這兩個方法`orElse()`和`orElseGet()`返回`Optional`對象的值,如果該對象為空,則返回作為參數傳遞給此方法的默認值。 ```java //Importing Optional class import java.util.Optional; ? public class Example {?? public static void main(String[] args) { //Creating Optional object from a String Optional<String> GOT = Optional.of("Game of Thrones");? ? ? ? //Optional.empty() creates an empty Optional object? ? ? ? Optional<String> nothing = Optional.empty(); //orElse() method System.out.println(GOT.orElse("Default Value")); System.out.println(nothing.orElse("Default Value")); //orElseGet() method System.out.println(GOT.orElseGet(() -> "Default Value")); System.out.println(nothing.orElseGet(() -> "Default Value")); } } ``` 輸出: ```java Game of Thrones Default Value Game of Thrones Default Value ``` ## Java 8 - `Optional.map`和`Optional.flatMap` 在這個例子中,我們將看到`Optional`如何與`map`和`flatMap`一起使用。 ```java //Importing Optional class import java.util.Optional;? public class Example {?? public static void main(String[] args) { //Creating Optional object from a String? ? ? ? Optional<String> GOT = Optional.of("Game of Thrones");? ? ? ? //Optional.empty() creates an empty Optional object? ? ? ? Optional<String> nothing = Optional.empty(); System.out.println(GOT.map(String::toLowerCase));? ? ? ? System.out.println(nothing.map(String::toLowerCase)); Optional<Optional<String>> anotherOptional = Optional.of(Optional.of("BreakingBad"));? ? ? ? System.out.println("Value of Optional object"+anotherOptional);? ? ? ? System.out.println("Optional.map: "? ? ? ? ? ? ? +anotherOptional.map(gender -> gender.map(String::toUpperCase)));? ? ? ? //Optional<Optional<String>>? ? -> flatMap -> Optional<String>? ? ? ? System.out.println("Optional.flatMap: "? ? ? ? ? ? ?+anotherOptional.flatMap(gender -> gender.map(String::toUpperCase))); } } ``` 輸出: ```java Optional[game of thrones] Optional.empty Value of Optional objectOptional[Optional[BreakingBad]] Optional.map: Optional[Optional[BREAKINGBAD]] Optional.flatMap: Optional[BREAKINGBAD] ``` ## 示例:`Optional`和過濾器 在這個例子中,我們將看到`Optional`如何與過濾器一起使用。要閱讀有關過濾器的信息,請參閱本指南: [Java 過濾器](https://beginnersbook.com/2017/10/java-8-stream-filter/)。 **有關過濾器的更多教程:** 1. [Java - 過濾映射](https://beginnersbook.com/2017/10/java-8-filter-a-map-by-keys-and-values/) 2. [從 Java 的流中過濾空值](https://beginnersbook.com/2017/10/java-8-filter-null-values-from-a-stream/) ```java //Importing Optional class import java.util.Optional;? public class Example {?? public static void main(String[] args) { //Creating Optional object from a String? ? ? ? Optional<String> GOT = Optional.of("Game of Thrones");? ? ? ??? ? ? ? /* Filter returns an empty Optional instance if the output doesn't? ? ? ? ? * contain any value, else it returns the Optional object of the?? ? ? ? ? * given value.? ? ? ? ? */? ? ? ? System.out.println(GOT.filter(s -> s.equals("GAME OF THRONES")));?? ? ? ? System.out.println(GOT.filter(s -> s.equalsIgnoreCase("GAME OF THRONES"))); } } ``` 輸出: ```java Optional.empty Optional[Game of Thrones] ``` **參考文獻:** [Java 8 - `Optional`類 JavaDoc](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看