Optional
类主要解决的问题是臭名昭著的空指针异常(NullPointerException
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| if (user != null) { Address address = user.getAddress(); if (address != null) { Country country = address.getCountry(); if (country != null) { String isocode = country.getIsocode(); if (isocode != null) { isocode = isocode.toUpperCase(); } } } }
String isocode = Optional.ofNullable(user) .map(User::getAddress) .map(Address::getCountry) .map(Country::getIsocode) .orElse("default");
|
orElse与orElseGet
of中值不为空,则orElseGet不执行函数,而orElse一定会执行的
1 2 3
| System.out.println(Optional.of("A").orElse(B())); System.out.println(Optional.of("A").orElseGet(() -> B())); System.out.println(Optional.ofNullable(null).orElseGet(() -> B()));
|
map
1 2 3
| Optional<String> name=Optional.of("Huang Dahui"); Optional<String> upperName = name.map(String::toUpperCase);
|
Predicate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); System.out.println("输出所有数据:"); eval(list, n->true); System.out.println("输出所有偶数:"); eval(list, n-> n%2 == 0 ); System.out.println("输出大于 3 的所有数字:"); eval(list, n-> n > 3 ); public static void eval(List<Integer> list, Predicate<Integer> predicate) { for(Integer n: list) { if(predicate.test(n)) { System.out.println(n + " "); } } }
|