Java 8: Difference between map and flatMap for null check style

For example, I have two model classes:

public class Person {}
public class Car {}

Now I have a method that accepts 2 optional parameters:

public void example1(Optional<Person> person, Optional<Car> car) {
    if (person.isPresent() && car.isPresent()) {
        processing(person.get(), car.get());
    }
}

Now I do not want to use a null check like this, I use flatMapand 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 in the above 2 customs? Since I think this is the same thing: if one value was null, java will stop execution and return.

thank

+4
source share
1 answer

, Optional<?>, Optional<Optional<?>> ( ? processing()). , .

, , ifPresent():

person.ifPresent(p -> car.ifPresent(c -> processing(p, c)));

, processing() void, .

+5

Source: https://habr.com/ru/post/1673348/


All Articles