Optional in Java

<p>Java introduced the `Optional` class in Java 8 to better handle null references. Optional is a container object that may or may not hold a value. The class then provides methods to operator on the data that it may contain.</p> <p>An Optional can be created for any data type in Java. For primitive data types, Optional is available as a variant for int, double and long in the form of `OptionalInt`, `OptionalDouble`, `OptionalLong`.</p> <p>However, These variants miss out on the map and filter methods which Optional provides, but these operations can be performed on these variants by converting them into a Stream using the&nbsp;<em>stream()</em>&nbsp;method</p> <p>To create an instance of Optional class, We need to use the static methods&nbsp;<em>of()</em>&nbsp;or&nbsp;<em>ofNullable()&nbsp;</em>with a value and an empty optional using the&nbsp;<em>empty()</em>&nbsp;method.</p> <pre> Optional&lt;String&gt; strOptional = Optional.of(&quot;data&quot;); Optional&lt;String&gt; emptyOptional = Optional.empty(); Optional&lt;String&gt; nullableOptional = Optional.ofNullable(null); //Returns Optional.EMPTY</pre> <p>Before the Optional class, A reference had to be checked for null value with an explicit null check, this can be replaced with a&nbsp;<em>isPresent()&nbsp;</em>call to check if a value is present in the Optional instance.</p> <pre> if(value != null) { System.out.println(value); }</pre> <p>can be replaced with</p> <pre> if(optionalValue.isPresent()) { System.out.println(optionalValue.get()); }</pre> <p>The above example can also written using the&nbsp;<em>ifPresent()</em>&nbsp;method, which takes a Consumer and is executed only if the Optional has a value.</p> <p><a href="https://medium.com/@developerguy25/optional-in-java-8fac3ee2c515">Website</a></p>
Tags: Coding Java