Saturday, 3 September 2016

Understanding and using Java 8 Optional class

Background

Java 8 has introduced a new class Optional which is kind of a container which may or maynot hold a value. You might ask whats the big deal? I might be as well and I might add null checks to avoid NPE. Think about it there is no clear way to suggest that null is a special value that can be returned whereas using Optional clearly indicates that the the value may not be present. Plus you can use functional programming with it - Lambdas and much more. Well see that in a moment.

Understanding

Method isPresent() is used to check if your Optional container has value or not. If it is there you can use get() method to retrieve it. Also notice how create a Optional instance. If it has to contain value you create it as Optional.of(value) other wise you use Optional.ofNullable(value) or Optional.empty(). Then you also have other useful methods like orElse(T other) which will return the value if it is present in Optional instance or return the argument supplied in method parameter. You have similar other methods - orElseGet(Supplier s), ifPresent(Consumer c), orElseThrow(Supplier s) that again uses functional programming. Have demoed most of them in code above. Others are similar and straightforward. You can see details of all methods in picture below.

Details of all the methods of Optional class are as follows -

Other uses

You can also use this in Spring framework as follows -

If you are using Spring 4.1 and Java 8 you can use java.util.Optional which is supported in @RequestParam, @PathVariable, @RequestHeader and @MatrixVariable in Spring MVC -