Optional的简单用法

2019-12-10  本文已影响0人  鱼da王
// 1. value可为null的Optional & orElseGet & orElse
Optional.ofNullable(null).orElse("默认结果");
Optional.ofNullable(null).orElseGet(() -> {
return "通过Supplier接口方法,默认的返回值";
});

// 2. value不可为null,throw npe
Optional.of(null);

// 3. Stream & Null  stream中没有元素
List<Integer> nomalList = new ArrayList<>();
System.out.println(nomalList.stream().findFirst().orElse(null));

// 4. Stream & Null , Stream中有null元素,throw npe
List<Integer> nullList = new ArrayList<>();
nullList.add(null);
System.out.println(nullList.stream().findFirst().orElse(null));

// 5. Stream有null元素. 某些函数会报NPE,例如findFirst()
// solve1: Optional.ofNullable,但是可能有No value present
Integer in = nullList.stream()
  .map(Optional::ofNullable)
  .findFirst()// 这个一步返回的是 Optional.of(Optional.ofNullable()), 所以在.get()时候,可能会出现No value present
  .get()
  .get();

// solve2: filter 保证此写法不会抛NPE,但是可能有No value present
Integer in1 = nullList.stream().filter(e -> e!= null).findFirst().get();

// solve3: filter 这个最安全
Optional<Integer> in2 = nullList.stream().filter(Objects::nonNull).findFirst();
if (in2.isPresent()) {
  Integer in22 = in2.get();
}
上一篇 下一篇

猜你喜欢

热点阅读