📅  最后修改于: 2020-11-15 03:16:48             🧑  作者: Mango
Java 8中引入了可选类,以避免空检查和NullPointerException问题。在Java 9中,添加了三个新方法来改善其功能。
public Stream stream()
如果存在值,则它返回仅包含该值的顺序Stream,否则返回空Stream。
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> 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 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 filteredListJava9 = list.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
System.out.println(filteredList);
System.out.println(filteredListJava9);
}
}
[A, B]
[A, B]
public void ifPresentOrElse(Consumer super T> action, Runnable emptyAction)
如果存在值,则使用该值执行给定的操作,否则执行给定的基于空的操作。
import java.util.Optional;
public class Tester {
public static void main(String[] args) {
Optional 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.
public Optional or(Supplier extends Optional extends T>> supplier)
如果存在值,则返回描述该值的Optional,否则返回由supplying函数产生的Optional。
import java.util.Optional;
import java.util.function.Supplier;
public class Tester {
public static void main(String[] args) {
Optional optional1 = Optional.of("Mahesh");
Supplier> 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