Reputation: 929
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
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
Upvotes: 0
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