Combination of Java 8 Options with Conditional AND

My problem: I have two or more options that wrap different types. I want to perform an operation that can only be performed if all options are not empty.

I am currently doing this:

    Optional<PatientCase> caseOptional = patientCaseRepository.findOneById(caseId);
    Optional<User> userOptional = userRepository.findOneById(caseId);

    if(userOptional.isPresent() && caseOptional.isPresent()) {
        caseOptional.get().getProcess().setDesigner(userOptional.get());
    }

In my opinion, the if condition does not seem to be correct. I know that you can bind Options using orElse. But in my case, I do not want a logical Else. Is there a way to create an AI operator to combine two or more options similar to this PSEUDO code?

caseOptional.and.userOptional.ifPresent((theCase,user) -> //Perform Stuff);
+4
source share
2 answers

, () Optional, , ( ) . .

caseOptional.flatMap(theCase -> userOptional
        .map(user -> new AbstractMap.SimpleEntry<>(theCase, user)))
    .ifPresent(e -> e.getKey().getProcess().setDesigner(e.getValue()));

AbstractMap.SimpleEntry stand-in .

:

caseOptional.flatMap(theCase -> userOptional
        .map(user -> Collections.singletonMap(theCase, user)))
    .ifPresent(m -> m.forEach((c, u) -> c.getProcess().setDesigner(u)));

caseOptional.map(PatientCase::getProcess)
            .ifPresent(p -> userOptional.ifPresent(p::setDesigner));

caseOptional.ifPresent(c -> userOptional.ifPresent(u -> c.getProcess().setDesigner(u)));

.

+5

.

Stram allMatch ifPresent :

Stream.of(optional1, optional2, ...).allMatch(Optional::isPresent)
+2

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


All Articles