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 <em>stream()</em> method</p>
<p>To create an instance of Optional class, We need to use the static methods <em>of()</em> or <em>ofNullable() </em>with a value and an empty optional using the <em>empty()</em> method.</p>
<pre>
Optional<String> strOptional = Optional.of("data");
Optional<String> emptyOptional = Optional.empty();
Optional<String> 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 <em>isPresent() </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 <em>ifPresent()</em> 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>