In JDK 8, Java presented the Optional class, which serves as a solution to handling NullPointerExceptions in Java programs. This class, defined as a public final class, requires the import of the java.util package for utilization. Optional offers a set of functions designed for verifying the existence of a value associated with a specific variable.
Java Optional Class Methods
| Methods | Description |
|---|---|
| public static public static <T> Optional<T> empty() OptionalOptional empty() | It returns an empty Optional object. No value is present for this Optional. |
| public static <T> Optional<T> of(T value) | It returns an Optional with the specified present non-null value. |
| public static <T> OptionalOptional ofNullable(T value) | It returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional. |
| public T get() | If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException. |
| public boolean isPresent() | It returns true if there is a value present, otherwise false. |
| public void ifPresent(Consumer<? super T> consumer) | If a value is present, invoke the specified consumer with the value, otherwise do nothing. |
| public OptionalOptional<T> filter(PredicatePredicate<? super T> predicate) | If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional. |
| public Optional<T> OptionalOptional map(FunctionFunction<? super T, ? extends U> mapper) | If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional. |
| public Optional<T> OptionalOptional<T> flatMap(FunctionFunction<? super T, ? extends Optional<? extends U>> mapper) | If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an empty Optional. |
| public T orElse(T other) | It returns the value if present, otherwise returns other. |
| public T orElseGet(Supplier<? extends T> other) | It returns the value if present, otherwise invoke other and return the result of that invocation. |
| public Optional<T> T orElseThrow(SupplierSupplier<? extends X> exceptionSupplier) throws X extends Throwable | It returns the contained value, if present, otherwise throw an exception to be created by the provided supplier. |
| public boolean equals(Object obj) | Indicates whether some other object is "equal to" this Optional or not. The other object is considered equal if:It is also an Optional and;Both instances have no value present or;the present values are "equal to" each other via equals(). |
| public int hashCode() | It returns the hash code value of the present value, if any, or returns 0 (zero) if no value is present. |
| public String toString() | It returns a non-empty string representation of this Optional suitable for debugging. The exact presentation format is unspecified and may vary between implementations and versions. |
- It is also an Optional and;
- Both instances have no value present or;
- the present values are "equal to" each other via equals.
Example: Java Program Without Using Optional
In this instance, the Optional class is omitted. As a result, the program ends abruptly and raises a NullPointerException.
File Name: OptionalExample.java
public class OptionalExample {
public static void main(String[] args) {
String[] str = new String[10];
String lowercaseString = str[5].toLowerCase();
System.out.print(lowercaseString);
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at lambdaExample.OptionalExample.main(OptionalExample.java:6)
In order to prevent unexpected program termination, the Optional class is utilized. The subsequent example demonstrates the use of Optional, ensuring the program can run smoothly without encountering any crashes.
Java Optional Example: If Value is not Present
File Name: OptionalExample.java
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
String[] str = new String[10];
Optional<String> checkNull = Optional.ofNullable(str[5]);
if(checkNull.isPresent()){ // check for value is present or not
String lowercaseString = str[5].toLowerCase();
System.out.print(lowercaseString);
}else
System.out.println("string value is not present");
}
}
Output:
string value is not present
Java Optional Example: If Value is Present
File Name: OptionalExample.java
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
String[] str = new String[10];
str[5] = "JAVA OPTIONAL CLASS EXAMPLE";// Setting value for 5th index
Optional<String> checkNull = Optional.ofNullable(str[5]);
if(checkNull.isPresent()){ // It Checks, value is present or not
String lowercaseString = str[5].toLowerCase();
System.out.print(lowercaseString);
}else
System.out.println("String value is not present");
}
}
Output:
java optional class example
Another Java Optional Example
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
String[] str = new String[10];
str[5] = "JAVA OPTIONAL CLASS EXAMPLE"; // Setting value for 5th index
Optional<String> checkNull = Optional.ofNullable(str[5]);
checkNull.ifPresent(System.out::println); // printing value by using method reference
System.out.println(checkNull.get()); // printing value by using get method
System.out.println(str[5].toLowerCase());
}
}
Output:
JAVA OPTIONAL CLASS EXAMPLE
JAVA OPTIONAL CLASS EXAMPLE
java optional class example
Java Optional Methods Example
File Name: OptionalExample.java
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
String[] str = new String[10];
str[5] = "JAVA OPTIONAL CLASS EXAMPLE"; // Setting value for 5th index
// It returns an empty instance of Optional class
Optional<String> empty = Optional.empty();
System.out.println(empty);
// It returns a non-empty Optional
Optional<String> value = Optional.of(str[5]);
// If value is present, it returns an Optional otherwise returns an empty Optional
System.out.println("Filtered value: "+value.filter((s)->s.equals("Abc")));
System.out.println("Filtered value: "+value.filter((s)->s.equals("JAVA OPTIONAL CLASS EXAMPLE")));
// It returns value of an Optional. if value is not present, it throws an NoSuchElementException
System.out.println("Getting value: "+value.get());
// It returns hashCode of the value
System.out.println("Getting hashCode: "+value.hashCode());
// It returns true if value is present, otherwise false
System.out.println("Is value present: "+value.isPresent());
// It returns non-empty Optional if value is present, otherwise returns an empty Optional
System.out.println("Nullable Optional: "+Optional.ofNullable(str[5]));
// It returns value if available, otherwise returns specified value,
System.out.println("orElse: "+value.orElse("Value is not present"));
System.out.println("orElse: "+empty.orElse("Value is not present"));
value.ifPresent(System.out::println); // printing value by using method reference
}
}
Output:
Optional.empty
Filtered value: Optional.empty
Filtered value: Optional[JAVA OPTIONAL CLASS EXAMPLE]
Getting value: JAVA OPTIONAL CLASS EXAMPLE
Getting hashCode: -619947648
Is value present: true
Nullable Optional: Optional[JAVA OPTIONAL CLASS EXAMPLE]
orElse: JAVA OPTIONAL CLASS EXAMPLE
orElse: Value is not present
JAVA OPTIONAL CLASS EXAMPLE
Using Alternate Values if Value is not Present: orElse and orElseGet
The functionalities of orElse and orElseGet in the Optional class of Java are designed to fetch a value from an Optional object if the value it holds is absent. While both methods serve comparable objectives, they vary slightly in their functioning. Below is a demonstration of how these methods are utilized in a Java code snippet.
File Name: OptionalOrElseExample.java
import java.util.Optional;
public class OptionalOrElseExample {
public static void main(String[] args) {
// Simulating a method that might return null
String nameFromDatabase = getUserNameFromDatabase();
// Convert the possibly null string to an Optional
Optional<String> optionalName = Optional.ofNullable(nameFromDatabase);
// Using orElse() to provide a default name
String nameWithOrElse = optionalName.orElse("Default User");
System.out.println("Name with orElse: " + nameWithOrElse);
// Using orElseGet() to provide a default name using a Supplier
String nameWithOrElseGet = optionalName.orElseGet(OptionalOrElseExample::getDefaultUserName);
System.out.println("Name with orElseGet: " + nameWithOrElseGet);
}
// A mock method to simulate database access that might return null
private static String getUserNameFromDatabase() {
// return null to simulate the absence of a user
return null;
}
// A method that provides a default username
private static String getDefaultUserName() {
// Simulate some expensive computation or fetching operation
System.out.println("Computing default username...");
return "Computed Default User";
}
}
Output:
Name with orElse: Default User
Computing default username...
Name with orElseGet: Computed Default User
Optional Value Transformation With map and flatMap
Using map Method
The map function is utilized to execute a function on the value held within the Optional in case it exists. Subsequently, the outcome is enclosed in a fresh Optional. This comes in handy for modifying the value while ensuring it remains within the Optional container.
File Name: OptionalFilterExample.java
import java.util.Optional;
public class OptionalMapExample {
public static void main(String[] args) {
// Example Optional containing a user's name
Optional<String> nameOptional = Optional.of("john doe");
// Use map to convert the name to uppercase
Optional<String> upperName = nameOptional.map(String::toUpperCase);
// Print the transformed name if it is present
upperName.ifPresent(System.out::println); // Output: JOHN DOE
}
}
Output:
JOHN DOE
Using flatMap Method
The flatMap function is utilized to implement a function on the value within the Optional. The function is required to yield an Optional as a result. This approach proves beneficial when aiming to circumvent nested Optional structures and achieve a streamlined Optional format.
File Name: OptionalFlatMapExample.java
import java.util.Optional;
public class OptionalFlatMapExample {
public static void main(String[] args) {
// Example Optional containing a user's name
Optional<String> nameOptional = Optional.of("john doe");
// Use flatMap to get the length of the name, wrapped in an Optional
Optional<Integer> nameLength = nameOptional.flatMap(name -> Optional.of(name.length()));
// Print the length if present
nameLength.ifPresent(length -> System.out.println("Name length: " + length)); // Output: Name length: 8
}
}
Output:
Name length: 8
Conditionally Returning Values With the filter Method
The filter function within Java's Optional class enables the selective retrieval of values based on a specified condition. It allows for the direct return of the Optional instance if the value meets the condition, or an empty Optional if it does not. This functionality proves beneficial for incorporating conditional logic seamlessly within a sequence of Optional actions, eliminating the necessity for explicit null validations or conditional constructs.
Basic Usage of filter Method
An illustration is provided below to showcase the implementation of filter for evaluating a condition on the stored value. Let's consider a situation where we need to verify whether a user's name is "admin" and take appropriate action depending on the outcome.
File Name: OptionalFilterExample.java
import java.util.Optional;
public class OptionalFilterExample {
public static void main(String[] args) {
// Example Optional containing a username
Optional<String> userOptional = Optional.of("admin");
// Use filter to check if the username is "admin"
Optional<String> filteredUser = userOptional.filter(username -> username.equals("admin"));
// Act based on the presence of the value
filteredUser.ifPresent(username -> System.out.println("User is an admin"));
// Output: User is an admin
// Let's check with a different username
Optional<String> anotherUser = Optional.of("john");
Optional<String> filteredAnotherUser = anotherUser.filter(username -> username.equals("admin"));
// This will print nothing since the filter condition is not met
filteredAnotherUser.ifPresent(username -> System.out.println("User is an admin"));
}
}
Output:
User is an admin