[英]Java 8: Difference between map and flatMap for null-checking style
For example I have two model class: 例如,我有两个模型类:
public class Person {}
public class Car {}
Now, I have a method that accepted 2 optional parameters: 现在,我有一个接受2个可选参数的方法:
public void example1(Optional<Person> person, Optional<Car> car) {
if (person.isPresent() && car.isPresent()) {
processing(person.get(), car.get());
}
}
Now, I don't want to use null-checking like this, I use flatMap
and map
. 现在,我不想像这样使用null检查,我使用flatMap
和map
。
person.flatMap(p -> car.map(c -> processing(p, c)));
person.map(p -> car.map(c -> processing(p, c)));
so my question is: are there any differences on above 2 usages? 所以我的问题是:上述两种用法有什么不同吗? Because I think that is the same: if one value were null, java will stop execute and return. 因为我认为是相同的:如果一个值为null,java将停止执行并返回。
Thanks 谢谢
The difference is only that one will return Optional<?>
and the other will return Optional<Optional<?>>
(replace ?
with the return type of processing()
). 区别仅在于一个将返回Optional<?>
而另一个将返回Optional<Optional<?>>
(用返回类型的processing()
替换?
)。 Since you're discarding the return type, there's no difference. 由于您丢弃了返回类型,因此没有区别。
But it's best to avoid the mapping functions, which by convention should avoid side-effects, and instead use the more idiomatic ifPresent()
: 但最好避免映射函数,按照惯例应该避免副作用,而是使用更惯用的ifPresent()
:
person.ifPresent(p -> car.ifPresent(c -> processing(p, c)));
This also works if processing()
has a void
return type, which isn't the case with a mapping function. 如果processing()
具有void
返回类型,这也适用,而映射函数则不然。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.