The Optional Class

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值