将空检查转换为可选
Convert null checks to Optional
我不明白如何以功能方式使用 Optional 更改这些空检查:
private boolean findProduct(String prodName) {
for(OrderItem item : orderItems) {
if(item != null) {
Product p=item.getProduct();
if(p != null) {
String name = p.getProductName();
if(name != null) {
if(name.equals(prodName)) return true;
}
}
}
}
return false;
}
使用Optional.ofNullable
and Optional.map
:
for(OrderItem item : orderItems) {
Optional<String> prod = Optional.ofNullable(item)
.map(OrderItem::getProduct)
.map(Product::getProductName)
.filter(s -> s.equals(prodName));
if (prod.isPresent()) {
return true;
}
}
return false;
请参阅 Optional.map
的 javadoc:
If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
您还可以使用 Stream API 来执行您想要的
public boolean findProductOptional(String productName) {
return orderItems
.stream()
.filter(Objects::nonNull)
.map(OrderItem::getProduct)
.filter(Objects::nonNull)
.anyMatch(product -> productName.equals(product.getProductName()));
}
简单地流式传输订单项目列表,映射到产品并检查是否存在具有给定名称的产品。
有点像上面答案的组合,你可以同时使用流和可选的(再加上它是一个单行)。
private boolean findProduct(String prodName) {
return orderItems.stream()
.map(Optional::ofNullable)
.anyMatch(o -> o
.map(OrderItem::getProduct)
.map(Product::getProductName)
.map(s -> s.equals(prodName))
.isPresent());
}
我不明白如何以功能方式使用 Optional 更改这些空检查:
private boolean findProduct(String prodName) {
for(OrderItem item : orderItems) {
if(item != null) {
Product p=item.getProduct();
if(p != null) {
String name = p.getProductName();
if(name != null) {
if(name.equals(prodName)) return true;
}
}
}
}
return false;
}
使用Optional.ofNullable
and Optional.map
:
for(OrderItem item : orderItems) {
Optional<String> prod = Optional.ofNullable(item)
.map(OrderItem::getProduct)
.map(Product::getProductName)
.filter(s -> s.equals(prodName));
if (prod.isPresent()) {
return true;
}
}
return false;
请参阅 Optional.map
的 javadoc:
If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
您还可以使用 Stream API 来执行您想要的
public boolean findProductOptional(String productName) {
return orderItems
.stream()
.filter(Objects::nonNull)
.map(OrderItem::getProduct)
.filter(Objects::nonNull)
.anyMatch(product -> productName.equals(product.getProductName()));
}
简单地流式传输订单项目列表,映射到产品并检查是否存在具有给定名称的产品。
有点像上面答案的组合,你可以同时使用流和可选的(再加上它是一个单行)。
private boolean findProduct(String prodName) {
return orderItems.stream()
.map(Optional::ofNullable)
.anyMatch(o -> o
.map(OrderItem::getProduct)
.map(Product::getProductName)
.map(s -> s.equals(prodName))
.isPresent());
}