January 1, 2021 A brief summary of how to use Java Optional.
Use this when you want to explicitly indicate that null may be returned as the return value of the method. It can be implemented more safely by showing that the method can return null.
You need to import java.util.Optional to use the Optional class. Generally, an object is defined and used. Optional objects are declared by specifying the type of the object that may be null in the Type Parameter without the diamond operator ('<>'). Specify the object name that may be null in the argument of the ofNullable method.
Basic writing
Optional<T>Object name= Optional.ofNullable(Object name that may be null);
Sample code
String str = null;
Optional<String> value = Optional.ofNullable(str);
The or method executes processing only when the object specified in the argument of the Optional.ofNullable method is null.
Sample code
import java.util.Optional;
public class Sample {
public static void main(String[] args) {
String str = null;
Optional<String> value = Optional.ofNullable(str);
System.out.println(value.or(() -> Optional.of("null")).get());
}
}
Execution result
null
If the argument of Optional.ofNullable method is null, the value is returned to the argument of orElse method. If it is not null, it returns its non-null value.
Sample code
import java.util.Optional;
public class Sample {
public static void main(String[] args) {
String str = null;
Optional<String> value = Optional.ofNullable(str);
str = value.orElse("null");
System.out.println(str);
}
}
Execution result
null
How to use Optional class in Java [For beginners] What is Java Optiona? Easy-to-understand explanation of how to use each pattern
Recommended Posts