In Java 8, we have a newly introduced Optional
class in java.util
package. This class is introduced to avoid NullPointerException that we frequently encounters if we do not perform null checks in our code. Using this class we can easily check whether a variable has null value or not and by doing this we can avoid the NullPointerException. In this guide, we will see how to work with Optional class and the usage of various methods of this class.
Before we see the example of Optional class, lets see what happens when we don’t use Optional class and do not perform null check.
Java Example: Without using Optional class
In this example, we didn’t assign the value to the String str and we are trying to get the substring out of it. Since there is no value present in the str, the program is throwing NullPointerException.
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); } }
Output:
Exception in thread "main" java.lang.NullPointerException at Example.main(Example.java:5)
Solution: Using Optional Class
Optional.ofNullable()
method of the Optional class, returns a Non-empty Optional if the given object has a value, otherwise it returns an empty Optional.
We can check whether the returned Optional value is empty or non-empty using the isPresent()
method.
//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"); } } }
Output:
Cannot get the substring from an empty string Substring is: raI
Example: Optional isPresent() vs ifPresent() methods
In the above example, we have seen that by using isPresent()
method we can check whether the particular Optional object(or instance) is empty or no-empty.
There is another method present in the Optional class, which only executes if the given Optional object is non-empty, the method is ifPresent()
. Lets see an example to understand the difference.
//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")); } }
Output:
Watching Game of Thrones Watching GOT is fun!
Java 8 – Optional orElse() and orElseGet() methods
These two methods orElse() and orElseGet() returns the value of Optional Object if it is no empty, if the object is empty then it returns the default value passed to this method as an argument.
//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")); } }
Output:
Game of Thrones Default Value Game of Thrones Default Value
Java 8 – Optional.map and Optional.flatMap
In this example, we will see how Optional works with map and flatMap.
//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))); } }
Output:
Optional[game of thrones] Optional.empty Value of Optional objectOptional[Optional[BreakingBad]] Optional.map: Optional[Optional[BREAKINGBAD]] Optional.flatMap: Optional[BREAKINGBAD]
Example: Optional with filter
In this example, we will see how Optional works with filter. To read about filters refer this guide: Java filters.
More tutorials on Filters:
//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"))); } }
Output:
Optional.empty Optional[Game of Thrones]
References:
Java 8 – Optional class JavaDoc
Leave a Reply