[英]Return Optional.empty instead of Optional[null] in Optional.map
In the below code, if customerInfo
is not present, it returns Optional[null] and hence customerInfo.get(name).textValue()
returns a NPE.在下面的代码中,如果
customerInfo
不存在,它会返回 Optional[null],因此customerInfo.get(name).textValue()
返回一个 NPE。 Is there a way to make map(data -> data.get("customerInfo"))
return Optional.empty()
instead of Optional[null]
?有没有办法让
map(data -> data.get("customerInfo"))
返回Optional.empty()
而不是Optional[null]
? Here the null within Optional[null]
is a NullNode object.这里
Optional[null]
中的 null 是一个 NullNode object。
Optional<JsonNode> orderData = getOrderData() // API Call
orderData.map(data -> data.get("customerInfo"))
.map(customerInfo -> customerInfo.get(name).textValue());
You seem to be misinterpreting the problem you're having.您似乎误解了您遇到的问题。 The NullPointerException occurs because
customerInfo.get(name)
is null, so customerInfo.get(name).textValue()
is trying to call the textValue()
method on a null reference. NullPointerException 发生是因为
customerInfo.get(name)
是 null,所以customerInfo.get(name).textValue()
试图在 null 引用上调用textValue()
方法。
To fix this, you can split that call to map
into two calls, like so:要解决此问题,您可以
map
的调用拆分为两个调用,如下所示:
orderData.map(data -> data.get("customerInfo"))
.map(customerInfo -> customerInfo.get(name))
.map(customer -> customer.textValue());
This way, if customerInfo.get(name)
is null, then the resulting Optional will be empty, and that last lambda won't be executed.这样,如果
customerInfo.get(name)
为 null,则生成的 Optional 将为空,并且不会执行最后一个 lambda。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.