他们之所以做得到,就因为他们认为他们能够做到。—— 维吉尔
关于Optional
的介绍,之前的博客已经说过了,这里就不再赘述
这里写点常用的例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| package com.ruben;
import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import java.util.stream.Stream;
public class OptionalDemo { public static void main(String[] args) { String str = null; System.out.println(Optional.ofNullable(str).map(""::equals).map(Boolean::getClass).map(Class::getName).orElseGet(String::new)); System.out.println(avoidNPE(() -> Boolean.valueOf(str.equals("")).equals(Boolean.FALSE)).orElse(false)); System.out.println(Optional.ofNullable(Arrays.asList()).map(List::stream).map(Stream::sorted).map(Stream::distinct).flatMap(Stream::findFirst).orElse("empty")); System.out.println(avoidNPE(() -> Arrays.asList().stream().sorted().distinct().findFirst().orElse("empty")).get()); List<String> list = null; avoidNPEOrIOB(list, 5).filter(s -> s.length() > 2).map(String::hashCode).ifPresent(System.out::println);
}
public static <T> Optional<T> avoidNPEOrIOB(List<T> list, int index) { try { return Optional.ofNullable(list.get(index)); } catch (NullPointerException | ArrayIndexOutOfBoundsException e) { return Optional.empty(); } }
public static <T> Optional<T> avoidNPE(Supplier<T> supplier) { try { return Optional.ofNullable(supplier.get()); } catch (NullPointerException e) { return Optional.empty(); } }
}
|
执行结果