Java'sOptional
is a container class introduced in Java 8, designed to handle more elegantly possible fornull
value to avoid explicitnull
Check and null pointer exceptions (NullPointerException
). Its core idea is to force developers to explicitly deal with situations where "values may not exist" rather than implicitly ignore them.
1. The core role of Optional
Explicitly means "values may be missing": The caller needs to process null values through the type system.
reducenull
Check the code: Provide chained methods instead of nestedif (obj != null)
。
Avoid null pointer exceptions: Access potential null values through a safe method.
2. Create Optional object
// 1. Create an Optional with a non-null value (NPE will be thrown if the value is null)Optional<String> optional1 = ("Hello"); // 2. Create an Optional that may be nullString value = getNullableValue(); // May return nullOptional<String> optional2 = (value); // 3. Create an empty OptionalOptional<String> optional3 = ();
3. Common methods of Optional
1. Check whether the value exists
-
isPresent()
: Determine whether the value exists. -
isEmpty()
(Java 11+): determine whether the value is empty.
if (()) { ("Value exists: " + ()); }
2. Perform an operation when the value exists
-
ifPresent(Consumer)
: Perform an operation when the value exists.
(v -> ("Value is: " + v));
3. Get the value
-
get()
: Get the value directly (if the value is empty, an exception will be thrown, so use it with caution). -
orElse(T)
: Returns the value when the value exists, otherwise returns the default value. -
orElseGet(Supplier)
: Delayed to generate default values. -
orElseThrow()
: An exception is thrown when the value does not exist (customizable exceptions).
String result = ("default value"); String result = (() -> generateDefault()); String result = (() -> new NotFoundException("The value does not exist"));
4. Chain operation
-
map(Function)
: Convert the value (if the value is empty, it will directly return to empty Optional). -
flatMap(Function)
: andmap
Similar, but used to return Optional. -
filter(Predicate)
: Filter the value, if the condition does not meet the condition, the return empty Optional.
Optional<String> upperCase = (String::toUpperCase); Optional<Integer> length = (v -> (())); Optional<String> filtered = (v -> () > 3);
4. Use scenarios
Method returns value: It is clear that the return value may be empty.
public Optional<User> findUserById(int id) { // Query the database, may return null return ((id)); }
Chain processing may be empty values:
String city = userOptional .map(User::getAddress) .map(Address::getCity) .orElse("Unknown City");
Substitutionif-else
Nesting:
// Traditional wayif (user != null && () != null) { // ... } // Optional method(User::getAddress).ifPresent(address -> { // ... });
5. Best practices and precautions
Avoid the following situations:
WillOptional
As a field, method parameter or collection element (defying the original intention of the design).
OveruseOptional
, resulting in redundancy of code.
Call directlyget()
Without checking whether the value exists.
Priority useorElse/orElseGet
SubstitutionisPresent()
:
// Not recommendedif (()) { return (); } else { return "default"; } // recommendreturn ("default");
Use with Stream:
List<String> names = () .map(user -> ().orElse("anonymous")) .collect(());
6. Complete example
public class OptionalDemo { public static void main(String[] args) { Optional<String> optional = (getNullableString()); String value = optional .map(String::toUpperCase) .filter(s -> () > 3) .orElse("DEFAULT"); (value); // Output "DEFAULT" or processed value } private static String getNullableString() { return () > 0.5 ? "hello" : null; } }
This is the end of this article about the introduction and usage of Java Optional. For more information about Java Optional usage, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!