mccarthyj
mccarthyj

Reputation: 929

How can I log a value in a Java Optional.of chain?

I'm using an Optional.of chain in Java to get a value,

Integer yearOfBirth = Optional.ofNullable(employee)
                              .map(Employee::getDateOfBirth)
                              .map(LocalDateTime::getYear())
                              .orElseThrow(new EmployeeException("Date of birth not set for {}", employee));

Is it possible to insert a log statement in the chain so that the date of birth is logged, without being consumed by the chain itself?

Upvotes: 1

Views: 70

Answers (2)

Akshansh Jain
Akshansh Jain

Reputation: 407

If you want to do it at multiple places, with different logics (logs or just any similar side-effect), you might benefit by adding a peek function in a common utility, as described in the below answer

How to peek on an Optional?

Upvotes: 0

Mureinik
Mureinik

Reputation: 310983

You can replace the getDayOfBirth reference with a lambda that logs it and then returns it:

Integer yearOfBirth = 
    Optional.of(employee)
            .map(e -> {
                   LocalDateTime dob = e.getDateOfBirth();
                   logger.info("Date of Birth is " + dob);
                   return dob;
             })
            .map(LocalDateTime::getYear())
            .orElseThrow(new EmployeeException("Date of birth not set for {}", employee));

Upvotes: 4

Related Questions