简体   繁体   English

Java 8:用于null检查样式的map和flatMap之间的区别

[英]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检查,我使用flatMapmap

    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.

相关问题 rxjava:flatmap 和 map 的区别 - rxjava: difference between flatmap and map Java 8 中的 map() 和 flatMap() 方法有什么区别? - What's the difference between map() and flatMap() methods in Java 8? Optional.flatMap 和 Optional.map 有什么区别? - What is the difference between Optional.flatMap and Optional.map? Mono.then 和 Mono.flatMap/map 之间的区别 - Difference between Mono.then and Mono.flatMap/map 为什么Eclipse null分析会忽略null检查语句:if(someObject!= null){…},而someObject是字段范围变量? - Why Eclipse null analysis ignore null-checking statement: if (someObject != null) {…}, when someObject is a field-scope variable? 为什么Eclipse JDT Null-Checking尊重Apache Commons Validate - Why does Eclipse JDT Null-Checking respect Apache Commons Validate 如何让IntelliJ IDEA了解我的空检查方法? - How can I make IntelliJ IDEA understand my null-checking method? Groovy和Java中MAP的区别 - Difference between MAP in Groovy and Java 检查哈希映射和迭代哈希映射中的键之间的区别 - Difference between checking hash map and iterating through keys in hash map 在 a.map() 与 Reactor 中的.flatMap() 中返回 null - Returning a null in a .map() versus .flatMap() in Reactor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM