mardi 8 septembre 2020

Replacing isPresent with ifPresent and orElse

I have the following logic in my method where I check for the value of an optional parameter, and depending on that I build another object.

AtomicReference<Employee> employeeValue = null;
    questions.forEach(question -> {
        if(question.isBoolean().isPresent()) {
            employeeValue.set(Employee.builder()
                    .withBooleanValue(Boolean.valueOf(question.value()))
                    .build());
        } else {
            employeeValue.set(Employee.builder()
                    .withStringValue(question.value())
                    .build());
        }
        Record record = Record.builder()
                .withId(question.id())
                .withValue(employeeValue.get())
                .build();
        answers.add(record);
    });

How can I replace the above with ifPresent and orElse? I'm using Java 8 and therefore ifPresentOrElse method is not available. If I am to use ifPresent and orElse separately with anonymous inner function, how do I go about it?

Any help would be much appreciated.

Aucun commentaire:

Enregistrer un commentaire