Java 9 - 改进Optional类介绍
Java 8中引入了可选(Optional)类,以避免空检查和NullPointerException问题。在Java 9中,添加了三个新方法来改善其功能。
- stream()
- ifPresentOrElse()
- or()
stream() 语法
public Stream<T> stream()
stream 方法的作用就是将 Optional 转为一个 Stream,如果该 Optional 中包含值,那么就返回包含这个值的 Stream,否则返回一个空的 Stream(Stream.empty())。
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Tester {
public static void main(String[] args) {
List<Optional<String>> list=Arrays.asList (
Optional.empty(),
Optional.of("A"),
Optional.empty(),
Optional.of("B"));
//filter the list based to print non-empty values
//if optional is non-empty, get the value in stream, otherwise return empty
List<String> filteredList=list.stream()
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
.collect(Collectors.toList());
//Optional::stream method will return a stream of either one
//or zero element if data is present or not.
List<String> filteredListJava9=list.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
System.out.println(filteredList);
System.out.println(filteredListJava9);
}
}
输出
[A, B]
[A, B]
ifPresentOrElse()语法
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
如果存在值,则使用该值执行给定的操作,否则执行给定的基于空的操作。
import java.util.Optional;
public class Tester {
public static void main(String[] args) {
Optional<Integer> optional=Optional.of(1);
optional.ifPresentOrElse( x -> System.out.println("Value: " + x),() ->
System.out.println("Not Present."));
optional=Optional.empty();
optional.ifPresentOrElse( x -> System.out.println("Value: " + x),() ->
System.out.println("Not Present."));
}
}
输出
Value: 1
Not Present.
or()语法
public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)
如果值存在,返回 Optional 指定的值,否则返回一个预设的值。
import java.util.Optional;
import java.util.function.Supplier;
public class Tester {
public static void main(String[] args) {
Optional<String> optional1=Optional.of("Mahesh");
Supplier<Optional<String>> supplierString=() -> Optional.of("Not Present");
optional1=optional1.or( supplierString);
optional1.ifPresent( x -> System.out.println("Value: " + x));
optional1=Optional.empty();
optional1=optional1.or( supplierString);
optional1.ifPresent( x -> System.out.println("Value: " + x));
}
}
输出
Value: Mahesh
Value: Not Present
链接:https://www.learnfk.com/article-java9/java9_optional_class_improvements
来源:Learnfk无涯私塾网
Hi LearnFk.com