Optional Class in Java
In Java, the Optional class is a container object that may or may not contain a non-null value. It is a generic class that was introduced in Java 8 to help avoid null pointer exceptions and improve code readability.In previous versions of Java, null values often caused NullPointerExceptions in code, making it difficult to handle and debug. The Optional class helps to solve this problem by providing a container that may or may not hold a non-null value.
Java Optional Class Methods:
The Optional class in Java provides several methods to work with values that may or may not be present. Here are some of the commonly used methods:
- of() – The method returns an Optional with the specified non-null value. For example:
Optional<String> optionalString = Optional.of("value");
- ofNullable() - The method returns an Optional describing the specified value if it is not null, otherwise returns an empty Optional. For example:
String str = null;
Optional<String> optionalString = Optional.ofNullable(str);
- isPresent() - The method returns true if the Optional contains a non-null value, otherwise returns false. For example:
Optional<String> optionalString = Optional.of("Hello World");
if (optionalString.isPresent()) {
System.out.println(optionalString.get()); // prints "Hello World"
}
- get() - The method returns the value if present, otherwise throws a NoSuchElementException. For example:
Optional<String> optionalString = Optional.of("Hello World");
System.out.println(optionalString.get()); // prints "Hello World"
- orElse() - The method returns the value if present, otherwise returns the specified default value. For example:
Optional<String> optionalString1 = Optional.of("Hello World");
Optional<String> optionalString2 = Optional.empty();
System.out.println(optionalString1.orElse("Default Value")); // prints "Hello World"
System.out.println(optionalString2.orElse("Default Value")); // prints "Default Value"
- orElseGet() - The method returns the value if present, otherwise returns the result of the specified supplier function. For example:
Optional<String> optionalString1 = Optional.of("Hello World");
Optional<String> optionalString2 = Optional.empty();
System.out.println(optionalString1.orElseGet(() -> "Default Value")); // prints "Hello World"
System.out.println(optionalString2.orElseGet(() -> "Default Value")); // prints "Default Value"
- orElseThrow() - The method returns the value if present, otherwise throws an exception created by the specified supplier function. For example:
Optional<String> optionalString1 = Optional.of("Hello World");
Optional<String> optionalString2 = Optional.empty();
System.out.println(optionalString1.orElseThrow(() -> new RuntimeException("Value not present"))); // prints "Hello World"
System.out.println(optionalString2.orElseThrow(() -> new RuntimeException("Value not present"))); // throws RuntimeException
- filter()-The method takes a predicate as an argument and returns an Optional containing the value if the predicate is true, and an empty Optional if the predicate is false.
Optional<String> optionalString1 = Optional.of("Hello World");
Optional<String> optionalString2 = optionalString1.filter(s -> s.startsWith("H"));
System.out.println(optionalString2.get()); // prints "Hello World"
- map()-The method takes a function as an argument and returns an Optional containing the result of applying the function to the value if the Optional contains a value, and an empty Optional if the Optional contains no value.
Optional<String> optionalString1 = Optional.of("Hello World");
Optional<Integer> optionalLength = optionalString1.map(String::length);
System.out.println(optionalLength.get()); // prints 11
Implementation that uses all of the methods:
FileName: OptionalExample.java
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
Optional<String> optionalString1 = Optional.of("Hello World");
Optional<String> optionalString2 = Optional.empty();
// Check if an Optional object contains a value
if (optionalString1.isPresent()) {
System.out.println("optionalString1 contains a value: " + optionalString1.get());
}
if (optionalString2.isPresent()) {
System.out.println("optionalString2 contains a value: " + optionalString2.get());
} else {
System.out.println("optionalString2 is empty");
}
// Get the value of an Optional object or a default value if it is empty
String value1 = optionalString1.orElse("Default Value");
String value2 = optionalString2.orElse("Default Value");
System.out.println("value1: " + value1);
System.out.println("value2: " + value2);
// Get the value of an Optional object or generate a default value using a supplier function
String value3 = optionalString1.orElseGet(() -> "Default Value");
String value4 = optionalString2.orElseGet(() -> "Default Value");
System.out.println("value3: " + value3);
System.out.println("value4: " + value4);
// Get the value of an Optional object or throw an exception if it is empty
try {
String value5 = optionalString1.orElseThrow(() -> new RuntimeException("Value not present"));
System.out.println("value5: " + value5);
String value6 = optionalString2.orElseThrow(() -> new RuntimeException("Value not present"));
System.out.println("value6: " + value6);
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
// Filter an Optional object using a predicate
Optional<String> filteredString = optionalString1.filter(s -> s.startsWith("H"));
System.out.println("filteredString: " + filteredString.orElse("No value found"));
// Map an Optional object to a different type
Optional<Integer> optionalLength = optionalString1.map(String::length);
System.out.println("optionalLength: " + optionalLength.get());
// FlatMap an Optional object to another Optional object
Optional<String> optionalString3 = Optional.of("Hello");
Optional<String> optionalString4 = optionalString3.flatMap(s -> Optional.of(s + " World"));
System.out.println("optionalString4: " + optionalString4.get());
}
}
Output:
optionalString1 contains a value: Hello World
optionalString2 is empty
value1: Hello World
value2: Default Value
value3: Hello World
value4: Default Value
value5: Hello World
Value not present
filteredString: Hello World
optionalLength: 11
optionalString4: Hello World