An Optional is a container object that represents a way of replacing a nullable T reference with a non-null value. An Optional may either contain a non-null T reference that allows to determine whether it contain a null value by using method ifPresent().
It allows to reduce the number of null pointer exceptions in Java systems, by adding the possibility to build more expressive APIs considering that sometimes return values are missing. It is not meant to be a mechanism to avoid all types of null pointers.
1 package com.java;
2
3 import java.util.Optional;
4
5 public class Example {
6
7 public static void main(String[] args) {
8 Optional<Integer> canBeEmpty1 = Optional.of(5);
9 System.out.println(canBeEmpty1.isPresent());
10 System.out.println(canBeEmpty1.get());
11
12 Optional<Integer> canBeEmpty2 = Optional.empty();
13 System.out.println(canBeEmpty2.isPresent());
14 }
15 }
In the above example, It allows to view Optional as a single value container that either contains a value or null. It doesn't replace every single null reference. Instead, it helps design more-comprehensible APIs so that by just reading the signature of a method, it allows to specify whether you can expect an optional value.
Creating Optional objects
1. | Optional.empty() |
2. | Optional.of() |
3. | Optional.ofNullable() |
Optional.empty()
An Optional method empty() allows to create empty optional object instead returns null. An object can be validated using ifPresent() method, it Optional object contain value, it returns true and perform operation on value, otherwise excluded.
1 package com.java;
2
3 import java.util.Optional;
4
5 public class Example {
6
7 public static void main(String[] args) {
8 Optional<Integer> possible = Optional.empty();
9
10 if(possible.isPresent()) {
11 System.out.println("Value present in Optional object !");
12 } else {
13 System.out.println("Value not presents !");
14 }
15 }
16 }
In the above example, an empty Optional object created by using Optional static method empty(). A optional object validated using ifPresent() that return boolean value true as object is empty. It skip, if block and execute else block.
Optional.of()
An Optional static method of() used to create Optional object with value. It does not allows to create Optional object without value. If null value passed to of() method, it throws NullPointerException immediately.
1 package com.java;
2
3 import java.util.Optional;
4
5 public class Example {
6
7 public static void main(String[] args) {
8 Optional<Integer> possible = Optional.of(5);
9 possible.ifPresent(System.out::println);
10
11
12 Optional<String> other = Optional.of(null);
13 }
14 }
In the above example, a Optional object created using Optional static method of() by passing an integer value. The optional object validated using ifPresent() that returns true as it contain value. Again, an of() method called by passing a null value that throws NullPointerException.
1 5
2 Exception in thread "main" java.lang.NullPointerException
3 at java.base/java.util.Objects.requireNonNull(Objects.java:233)
4 at java.base/java.util.Optional.of(Optional.java:113)
5 at com.java.Example.main(Example.java:11)
Optional.ofNullable()
A Optional static method ofNullable() method used to create object that may hold a null value. If specified parameter is null, the resulting Optional object would be empty(remember that value is absent, it don’t read null).
1 package com.java;
2
3 import java.util.Optional;
4
5 public class Example {
6
7 public static void main(String[] args) {
8
9
10 Optional<Integer> possible_null = Optional.ofNullable(null);
11 possible_null.ifPresent(System.out::println);
12
13
14 Optional<Integer> possible_NoNull = Optional.ofNullable(5);
15 possible_NoNull.ifPresent(System.out::println);
16 }
17 }
In the above example, a Optional object created by passing a null value to ofNullable() method that create empty optional object. Hence, it does not print value. A next object created by passing an integer value to ofNullable() method that object with value. Hence, it print value.
Default/absent values and actions
A typical pattern in programming is to return a default value if you determine that the result of an operation may be null. To handle such scenario, ideally we are going to use ternary operator. A same code can be written using Optional object as below.
Default/absent values and actions
1 import java.util.Optional;
2
3 public class Example {
4
5 public void print() {
6 System.out.println("Default operation performed !");
7 }
8
9 public static void main(String[] args) {
10
11
12 Optional<Example> optional = Optional.empty();
13
14
15 Example example = optional.orElse(new Example());
16 example.print();
17
18
19 Example example1 = optional.orElseThrow(IllegalStateException::new);
20 }
21 }
In the above example, lets assume that we are performing some operation that may returns null instead of object. A Optional object method orElse() used to validate whether an optional object does not contain value. If it does not include value, it perform operation specified in ofElse() method. It return new Example object that perform operation using alternate object.
If you want to throw a custom exception, an optional method orElseThrow() used to throw a specified exception.
1 Default operation performed !
2 Exception in thread "main" java.lang.IllegalStateException
3 at java.base/java.util.Optional.orElseThrow(Optional.java:403)
4 at com.java.Example.main(Example.java:20)
Filtering value using filter method
Sometime, it requires to validate object before you perform operation on object. The filter() method used to validate object that filter object by validating object against predicate passed in the argument. If an object present in the Optional object matches the predicate, the filter method returns that object and perform operation.
Filtering value using filter method
1 package com.java;
2
3 import java.util.Optional;
4
5 public class Example {
6
7 public String getDept() {
8 return "Finance";
9 }
10
11 public static void main(String[] args) {
12
13 Optional<?> optional = Optional.of(new Example());
14 optional.filter(department -> "Finance".equals(((Example) department).getDept()))
15 .ifPresent(System.out::println);
16 }
17
18 @Override
19 public String toString() {
20 return "Example Object";
21 }
22 }
In the above example, a Optional object is created by passing a Example class object. The filter() method of Optional object validate against specified predicate action and returns boolean value, if it validated. The resulting object will be printed. It prints Example Object as toString() method return string instead object reference.
Related options for your search