Trần Kim Dự
Trần Kim Dự

Reputation: 6102

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

Upvotes: 4

Views: 1140

Answers (1)

shmosel
shmosel

Reputation: 50746

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.

Upvotes: 5

Related Questions