如何以更好的方式使用可选重写空检查
How can I rewrite null checks with optional in a better way
我有一小段代码。我想用更少的嵌套检查以更好的方式编写它。我怎样才能实现它?
Item item = itemResponse.getItem();
Optional<Item> optionalItem = Optional.ofNullable(item);
if (optionalItem.isPresent()) {
List<NameValue> listValues = item.getValues();
Optional<List<NameValue>> optionalListValues = Optional.ofNullable(listValues);
if (optionalListValues.isPresent()) {
System.out.println(listValues);
}
}
有什么简洁的方法可以用Java8重写上面的代码吗?
您可以将 itemResponse.getItem()
class 转换为 return Optional<Item>
并使用链式 map 方法,该方法仅在 Optional
具有值,如果 map
方法 return 非空值,则仅执行最终 ifPresent(Consumer consumer)
Optional<Item> item = itemResponse.getItem()
item.map(item::getValues)
.ifPresent(System.out::println);
我有一小段代码。我想用更少的嵌套检查以更好的方式编写它。我怎样才能实现它?
Item item = itemResponse.getItem();
Optional<Item> optionalItem = Optional.ofNullable(item);
if (optionalItem.isPresent()) {
List<NameValue> listValues = item.getValues();
Optional<List<NameValue>> optionalListValues = Optional.ofNullable(listValues);
if (optionalListValues.isPresent()) {
System.out.println(listValues);
}
}
有什么简洁的方法可以用Java8重写上面的代码吗?
您可以将 itemResponse.getItem()
class 转换为 return Optional<Item>
并使用链式 map 方法,该方法仅在 Optional
具有值,如果 map
方法 return 非空值,则仅执行最终 ifPresent(Consumer consumer)
Optional<Item> item = itemResponse.getItem()
item.map(item::getValues)
.ifPresent(System.out::println);