简体   繁体   中英

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:

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 .

    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.

Thanks

The difference is only that one will return Optional<?> and the other will return Optional<Optional<?>> (replace ? with the return type of 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() :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM