Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Importance of Optional.or() method in Java 9?
In Java 9, few static methods: stream(), or(), and ifPresentOrElse() have added to Optional<T> class. The introduction of an Optional class solves the null pointer exception.
Optional.or() method returns an Optional describing the value if a value is present, otherwise returns an Optional produced by the supplying function.
Syntax
public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)
Example
import java.util.Optional;
import java.util.function.Supplier;
public class OptionalOrTest {
public static void main(String args[]) {
Optional<String> optional = Optional.of("TutorialsPoint");
Supplier<Optional<String>> supplierString = () -> Optional.of("Not Present");
optional = optional.or(supplierString);
optional.ifPresent(x -> System.out.println("Value: " + x));
optional = Optional.empty();
optional = optional.or(supplierString);
optional.ifPresent(x -> System.out.println("Value: " + x));
}
}
Output
Value: TutorialsPoint Value: Not Present
Advertisements
