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?
Optionalat all?Stream, you may use itspeekmethod, but it’s probably not worth it. You would need to go.stream() .peek(...) ... .findAny() .orElseThrow(...).log.info("dob {}", employee.getDateOfBirth());before creating theOptional? Also, if your chain throws, you know there isn’t a date of birth, and if it doesn’t, you know there is (only you only know the year).