1、场景:从流里面查找数据
- boolean anyMatch(Predicate check)
Returns true if there is any elements in the stream that matches the given predicate.
Returns false if the stream is empty or if there are no matching elements.
- boolean allMatch(Predicate check)
Returns true only if all elements in the stream matches the given predicate.
Returns true if the stream is empty without evaluating the predicate!
- boolean noneMatch(Predicate check)
Returns true only if none of the elements in the stream matches the given predicate.
Returns true if the stream is empty without evaluating the predicate!
- Optional findFirst()
Returns the first element from the stream; if there is no element present in the stream, it returns an empty Optional object.
- Optional findAny()
Returns one of the elements from the stream; if there is no element present in the stream, it returns an empty Optional object.
2、创建Optional对象的三种方式
- 使用Optional类的工厂方法创建Optional对象:
Optional<String> empty = Optional.empty();
Optional<String> nonEmptyOptional = Optional.of("abracadabra");
//但是你不能把null传给of
Optional<String> nullStr = Optional.of(null);
System.out.println(nullStr);
// crashes with a NullPointerException
但是如果你想把null传给Optional,你可以用ofNullable方法
Optional<String> nullableStr = Optional.ofNullable(null);
System.out.println(nullableStr);
// prints: Optional.empty
3、Optional Stream
Listing 6-4. OptionalStream.java
import java.util.Optional;
public class OptionalStream {
public static void main(String []args) {
Optional<String> string = Optional.of(" abracadabra ");
string.map(String::trim).ifPresent(System.out::println);
}
}
This program prints:
abracadabra
4、Optional Stream抛出异常
Optional<String> string = Optional.ofNullable(null);
System.out.println(string.map(String::length).orElseThrow(IllegalArgumentException::new));
5、Optional<T>泛型的原始类型
public static void selectHighestTemperature(Stream<Double> temperatures) {
Optional<Double> max = temperatures.max(Double::compareTo);
if(max.isPresent()) {
System.out.println(max.get());
}
}
// 体会Stream<Double>和DoubleStream,Optional<Double>和OptionalDouble
public static void selectHighestTemperature(DoubleStream temperatures) {
OptionalDouble max = temperatures.max();
max.ifPresent(System.out::println);
}
selectHighestTemperature(DoubleStream.of(24.5, 23.6, 27.9, 21.1, 23.5, 25.5, 28.3))
28.3