January 2, 2021 Yesterday's article Similarly, I will briefly summarize how to use Java's Optional class. I will introduce how to use it with a method that I did not deal with yesterday.
The orElseThrow method processes differently depending on the presence or absence of arguments.
If there is no argument, it throws NoSuchElementException when it is null and returns a value when it is not null.
With no arguments
import java.util.NoSuchElementException;
import java.util.Optional;
public class Sample {
public static void main(String[] args) {
String str = null;
Optional<String> value = Optional.ofNullable(str);
try {
str = value.orElseThrow();
System.out.println(str);
} catch (NoSuchElementException ex) {
System.out.println("null");
}
}
}
Execution result
null
If there is an argument, you can specify an object of exception class through which the exception is passed.
With arguments
import java.util.Optional;
public class Sample {
public static void main(String[] args) {
String str = null;
Optional<String> value = Optional.ofNullable(str);
try {
System.out.println(value.orElseThrow(() -> new RuntimeException()));
} catch (RuntimeException e) {
System.out.println("null");
}
}
}
Execution result
null
It is possible to extract only non-null objects from Optional type objects without checking for null.
import java.util.List;
import java.util.Optional;
public class Sample {
public static void main(String[] args) {
List<String> list1 = List.of("Tanaka", "Yamada");
List<String> list2 = null;
Optional<List<String>> value1 = Optional.ofNullable(list1);
Optional<List<String>> value2 = Optional.ofNullable(list2);
value1.stream().flatMap(x -> x.stream()).forEach(System.out::println);
value2.stream().flatMap(x -> x.stream()).forEach(System.out::println);
}
}
Execution result
Tanaka
Yamada
Performs the process specified in the argument only when it is not null.
import java.util.Optional;
public class Sample {
public static void main(String[] args) {
String str = null;
Optional<String> value = Optional.ofNullable(str);
value.ifPresent(System.out::println);
}
}
Execution result
No processing is done because str is null
Processing can be performed even if it is null. Specify the processing when it is not null in the first argument, and specify the processing when it is null in the second argument.
import java.util.Optional;
public class Sample {
public static void main(String[] args) {
String str = null;
Optional<String> value = Optional.ofNullable(str);
value.ifPresentOrElse(
System.out::println,
() -> System.out.println("null"));
}
}
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