{"id":8017,"date":"2022-12-06T23:28:33","date_gmt":"2022-12-07T04:28:33","guid":{"rendered":"https:\/\/springframework.guru\/?p=8017"},"modified":"2024-10-20T08:23:36","modified_gmt":"2024-10-20T12:23:36","slug":"how-to-use-the-java-optional","status":"publish","type":"post","link":"https:\/\/springframework.guru\/how-to-use-the-java-optional\/","title":{"rendered":"How to Use the Java Optional Properly"},"content":{"rendered":"<p>One of the exceptions that every Java Programmer must have faced is <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/17\/docs\/api\/java.base\/java\/lang\/NullPointerException.html\" target=\"_blank\" rel=\"noopener\">NullPointerException<\/a>. They are hard to debug and cause unexpected termination of your application. To better handle <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">NullPointerException<\/code>, Java 8 has introduced the Optional class.<br \/>\nIn this post, I\u2019ll explain how to use <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> in Java applications.<\/p>\n<h2>Optional Overview<\/h2>\n<p>The main benefit of the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> class is that it prevents unwanted <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">NullPointerExceptions<\/code>.<\/p>\n<p>Consider this code.<\/p>\n<p><strong>NPEExample.java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">package guru.springframework.optionaldemos;\n\npublic class NPEExample {\n\n    static String convert(String[] strArr, int index){\n        if(strArr[index]!=null)\n           return strArr[index].toUpperCase();\n        else\n            return \"Please provide valid input\";\n    }\n    public static void main(String[] args) {\n        String[] strArr= new String[5];\n        String convertedValue= convert(strArr,3);\n        System.out.println(convertedValue);\n    }\n}<\/pre>\n<p>When you run the preceding code, you get <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">NullPointerException<\/code>, like this.<\/p>\n<p><a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2022\/12\/NullPointerException.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-large wp-image-8018\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2022\/12\/NullPointerException-1024x197.png\" alt=\"\" width=\"1024\" height=\"197\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2022\/12\/NullPointerException-1024x197.png 1024w, https:\/\/springframework.guru\/wp-content\/uploads\/2022\/12\/NullPointerException-300x58.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2022\/12\/NullPointerException-768x148.png 768w, https:\/\/springframework.guru\/wp-content\/uploads\/2022\/12\/NullPointerException-1536x295.png 1536w, https:\/\/springframework.guru\/wp-content\/uploads\/2022\/12\/NullPointerException-848x163.png 848w, https:\/\/springframework.guru\/wp-content\/uploads\/2022\/12\/NullPointerException-410x79.png 410w, https:\/\/springframework.guru\/wp-content\/uploads\/2022\/12\/NullPointerException.png 1822w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/a><\/p>\n<p>To prevent this, we can do explicit null checks, like this.<br \/>\n<strong> NPEExample.java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">package guru.springframework.optionaldemos;\n\npublic class NPEExample {\n\n    static String convert(String[] strArr, int index){\n        if(strArr[index]!=null)\n           return strArr[index].toUpperCase();\n        else\n            return \"Please provide valid input\";\n    }\n    public static void main(String[] args) {\n        String[] strArr= new String[5];\n        String convertedValue= convert(strArr,3);\n        System.out.println(convertedValue);\n    }\n}\n<\/pre>\n<p>With <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code>, the code will now look like this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">String res;\nString[] strArr= new String[6];\nOptional&lt;String&gt; checkNull = Optional.ofNullable(strArr[5]);\nif (checkNull.isPresent()) {\n    res = convert(strArr, 5);\n    System.out.println(res);\n}\nelse\nSystem.out.println(\"Value is not present\");\n<\/pre>\n<p>In the preceding code, the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ofNullable()<\/code> method returns an <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> describing the given value, if non-null. Otherwise, this method returns an empty <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code>. In the preceding code the method returns an empty <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code>.<\/p>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">isPresent()<\/code> method returns <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">true<\/code> if a value is present. Otherwise, it returns <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">false<\/code>. In the preceding code, the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">isPresent()<\/code> method will return <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">false<\/code>, and the program will output <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Value is not present<\/code>.<\/p>\n<h2>Creating Optional Objects<\/h2>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> class comes with a number of static methods to create <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> objects. The methods are:<\/p>\n<ul>\n<li><code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">empty()<\/code><\/li>\n<li><code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">of()<\/code><\/li>\n<li><code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ofNullable()<\/code><\/li>\n<\/ul>\n<h3>The empty() Method<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">private static void emptyOptioal() {\n    \/*Empty Optional*\/\n    Optional&lt;String&gt; empty = Optional.empty();\n    if(empty.isEmpty()){\n        System.out.println(\"I am an empty optional\");\n}\n<\/pre>\n<p>The preceding code returns an empty <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code>. No value is present for this <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code>.<\/p>\n<p><strong>Note<\/strong>: Though, it may be tempting to do check for presence, avoid testing if an object is empty by comparing with {==} against instances returned by <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Option.empty()<\/code>. There is no guarantee that it is a singleton. Instead, use <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">isPresent()<\/code>.<\/p>\n<h3>The of() Method<\/h3>\n<p>The next method is <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">of()<\/code>. This method returns an <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> with the specified present non-null value.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">private static void optionalOf() {\n    String name = \"Optional\";\n    Optional&lt;String&gt; opt = Optional.of(name);\n    System.out.println(opt);\n}\n<\/pre>\n<p>The preceding <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">of()<\/code> method expects a non-null argument. Otherwise, it will throw a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">NullPointerException<\/code>. So take precaustion of caaling this method, if you are not sure whether the parameter is null or not null.<\/p>\n<p>The best practice is to use the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ofNullable()<\/code> method.<\/p>\n<h3>The ofNullable() Method of the Optional Class<\/h3>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ofNullable ()<\/code> method returns an <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> describing the specified value, if non-null, otherwise returns an empty <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code>.<\/p>\n<p>You can refactor your code like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">\/\/ Possible null value\nOptional&lt;String&gt; optional = Optional.ofNullable(getName());\n\nprivate static String getName(){\n    String name = \"Im an Optional\";\n    return (name.length() &gt; 5) ? name :  null;\n}\n<\/pre>\n<p>In the preceding code, if we pass in a null reference, it doesn\u2019t throw an exception but rather returns an empty <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> object:<\/p>\n<p>Below is the code, you can refer to.<\/p>\n<p><strong>OptionalCreation.java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">package guru.springframework.optionaldemos;\n\nimport java.util.Optional;\n\npublic class OptionalCreation {\n\n    public static void main(String[] args) {\n        emptyOptioal();\n        optionalOf();\n        \/\/ Possible null value\n        Optional&lt;String&gt; optional = Optional.ofNullable(getName());\n        System.out.println(optional);\n\n\n    }\n    private static String getName(){\n        String name = \"Im an Optional\";\n        return (name.length() &gt; 5) ? name :  null;\n    }\n\n    private static void optionalOf() {\n        String name = \"Optional\";\n        Optional&lt;String&gt; opt = Optional.of(name);\n        System.out.println(opt);\n    }\n\n    private static void emptyOptioal() {\n        \/*Empty Optional*\/\n        Optional&lt;String&gt; empty = Optional.empty();\n        if(empty.isEmpty()){\n            System.out.println(\"I am an empty optional\");\n        }\n    }\n}\n<\/pre>\n<h2>Checking for Values in an Optional<\/h2>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> class has two methods called <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">isEmpty()<\/code> and <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">isPresent()<\/code>. Both the methods return a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">boolean<\/code> value which indicates whether or not a value is present in the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code>.<\/p>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">isEmpty()<\/code> method checks If a value is not present, and accordingly will returns <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">true<\/code>, otherwise <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">false<\/code>.<\/p>\n<p>On the other hand, the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">isPrsent()<\/code> method returns true If a value is present,, otherwise false.<\/p>\n<p>The code to use the methods is this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">Optional op1 = Optional.empty();\nSystem.out.println(op1.isEmpty());\nSystem.out.println(op1.isPresent());\nOptional op2 = Optional.of(\"Optional\");\nSystem.out.println(op2.isEmpty());\nSystem.out.println(op2.isPresent());\n<\/pre>\n<p>The output of the preceding code is this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">true\nfalse\nfalse\ntrue\n<\/pre>\n<h2>OrElse() and OrElseGet() of the Optional Class<\/h2>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<code> comes with the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">orElse()<\/code> method that will always call the given function whether you want it or not. It is also regardless of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional.isPresent()<\/code> value.<\/code><\/code><\/p>\n<p>The following code shows an example of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">orElse()<\/code> method.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">Optional&lt;Integer&gt; op  = Optional.empty();\n\/\/ print value\nSystem.out.println(\"Optional: \" + op);\n\nif(op.isEmpty())\n        \/\/ orElse value\n        System.out.println(\"Value by orElse \" + op.orElse(100));\n\n<\/pre>\n<p><strong>Note<\/strong>: On the other hand, <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">orElseGet()<\/code> will only call the given function when the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional.isPresent() == false<\/code>.<\/p>\n<h2>Retrieving Values from Optional<\/h2>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> class provides a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">get()<\/code> method that returns the value if present in the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code>. Otherwise, this method throws <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">NoSuchElementException<\/code>.<\/p>\n<p>The following code shows using the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">get()<\/code> method.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">package guru.springframework.optionaldemos;\n\nimport java.util.Optional;\n\npublic class OptionalGet {\n    public static void main(String[] args) {\n        Optional op1 = Optional.of(\"Hello World\");\n        System.out.println(op1.orElse(\"Default Value\"));\n        Optional opt2=Optional.empty();\n        System.out.println(opt2.orElse(\"Default Value\"));\n\n    }\n}\n<\/pre>\n<p>The output of the preceding code is this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Hello World\nException in thread \"main\" java.util.NoSuchElementException: No value present\n  at java.base\/java.util.Optional.get(Optional.java:143)\n  at guru.springframework.optionaldemos.OptionalGet.main(OptionalGet.java:10)\n<\/pre>\n<p>To avoid the exception, you can use the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">orElse()<\/code> method to return a default value, like this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">Optional op1 = Optional.of(\"Hello World\");\nSystem.out.println(op1.orElse(\"Default Value\"));\nOptional opt2=Optional.empty();\nSystem.out.println(opt2.orElse(\"Default Value\"));\n<\/pre>\n<p>The output of the preceding code is this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Hello World\nDefault Value\n<\/pre>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> class provides a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">orElseThrow()<\/code> method that you can use to throw a custom exception when a value is not present in the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code>.<\/p>\n<p>An example to use the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">orElseThrow()<\/code> method is this.<\/p>\n<p><strong>OptionOrElseThrow.java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">package guru.springframework.optionaldemos;\n\nimport java.util.Optional;\n\npublic class OptionOrElseThrow {\n\n    public static void main(String[] args) throws Throwable {\n        String email= null;\n        Optional emailOpt=Optional.ofNullable(email);\n        System.out.println(emailOpt.orElseThrow(()-&gt;new IllegalArgumentException(\"Email cannot be null\")));\n    }\n}\n<\/pre>\n<pre style=\"background: white;\"><span style=\"font-size: 14.5pt; font-family: 'Cambria',serif; color: #222635; background: white;\">The output on running the preceding code is this.\n<\/span><\/pre>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Exception in thread \"main\" java.lang.IllegalArgumentException: Email cannot be null<\/pre>\n<h2>Performing Operations on Optional<\/h2>\n<h3>The filter() Method<\/h3>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> class contains a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">filter()<\/code> method that filters a value, if present, against a given predicate. This method returns an <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> describing the value.<\/p>\n<p>If there is no value present in the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code>, then this method returns an empty <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> object.<\/p>\n<p>An example of using the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">filter()<\/code> method is this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\"> private static void filterDemo() {\n        Optional opt1=Optional.of(\"Hello! Optional Example\");\n        Predicate&lt;String&gt; predicate1 = s -&gt; s.contains(\"Example\");\n        Optional&lt;String&gt; result1 = opt1.filter(predicate1);\n        System.out.println(result1.isPresent());\n\n        Predicate&lt;String&gt; predicate2 = s -&gt; s.startsWith(\"Hello\");\n        Optional&lt;String&gt; result2 = opt1.filter(predicate2);\n        System.out.println(result2.isPresent());\n}<\/pre>\n<p>The output of the preceding code is this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">true\ntrue\n<\/pre>\n<h3>The map() Method<\/h3>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">map()<\/code> method of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> returns an <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> describing the result of applying the given mapping function to the value in the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code>. If no value is present this method returns an empty <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code>.<\/p>\n<p>The following code shows the use of the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">map()<\/code> method.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">private static void mapDemo() {\n        Optional&lt;String&gt; opt1=Optional.of(\"Hello! Optional Example\");\n        System.out.println(opt1.map(String::toUpperCase).get());\n}<\/pre>\n<p>The output on calling the preceding method is this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">HELLO! OPTIONAL EXAMPLE<\/pre>\n<h2>Summary<\/h2>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> class is an attempt to reduce the number of null pointer exceptions in Java systems. However, I have seen developers using <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> incorrectly.<\/p>\n<p>One common mistake is assigning null to an optional variable, like this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">public Optional&lt;Product&gt; getProduct(int id) {\n    \/\/ perform a search for product \n   Optional&lt;Product&gt; product = null; \/\/ in case no product\n   return product; \n\n}\n<\/pre>\n<p>The correct approach is to replace the line, which initializes the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> with an empty <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional like this.<\/code><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">Optional&lt;Product&gt; product = Optional.empty();<\/pre>\n<p>Another typical mistake developers make is directly calling the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">get()<\/code> method. If the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Optional<\/code> is empty, the call to get will throw <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">NoSuchElementException<\/code>. Instead always do a check with the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">isPresent()<\/code> method before calling <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">get()<\/code>.<\/p>\n<p>The source code of this post is present on <a href=\"https:\/\/github.com\/spring-framework-guru\/sfg-blog-posts\/tree\/master\/optionaldemo\" target=\"_blank\" rel=\"noopener\">Github<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>One of the exceptions that every Java Programmer must have faced is NullPointerException. They are hard to debug and cause unexpected termination of your application. To better handle NullPointerException, Java 8 has introduced the Optional class. In this post, I\u2019ll explain how to use Optional in Java applications. Optional Overview The main benefit of the [&hellip;]<a href=\"https:\/\/springframework.guru\/how-to-use-the-java-optional\/\" class=\"df-link-excerpt\">Continue reading<\/a><\/p>\n","protected":false},"author":111,"featured_media":4653,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[20,32],"tags":[414,413,412],"class_list":["post-8017","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","category-object-oriented-programming","tag-java-8-optional","tag-java-optional","tag-optional"],"jetpack_publicize_connections":[],"aioseo_notices":[],"modified_by":"jt","jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/springframework.guru\/wp-content\/uploads\/2017\/07\/Banner560x292_08Web.jpg","jetpack_shortlink":"https:\/\/wp.me\/p5BZrZ-25j","_links":{"self":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/8017"}],"collection":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/users\/111"}],"replies":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/comments?post=8017"}],"version-history":[{"count":7,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/8017\/revisions"}],"predecessor-version":[{"id":8198,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/8017\/revisions\/8198"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media\/4653"}],"wp:attachment":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media?parent=8017"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/categories?post=8017"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/tags?post=8017"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}