2

I have a method which returns Optional. Basically, it gets value from DB and if the value from DB is present and if the value is before 20 years, it returns currentDate-20 years or else return as it is.

Optional<Instant> getJoinDate(final Instant instant) {

        final Optional<Employee> joinTime = empService.retrieveById(1);

        if (joinTime.isPresent()) {

            final Instant joinDate = joinTime.get().getJoinTime().toInstant();

            if (joinDate.isBefore(instant.minus(20,ChronoUnit.YEARS))) {
                return Optional.of(instant.minus(20, ChronoUnit.YEARS));
            }
            else {
                return Optional.of(joinDate);
            }
        }

        return Optional.empty();
    }

Is there any simple way to do this with Java 8 without if else?

Thanks

2 Answers 2

3

You can use flatMap:

Optional<Instant> getJoinDate(final Instant instant) {
    final Optional<Employee> joinTime = empService.retrieveById(1);
    return joinTime.flatMap (emp -> {
        final Instant joinDate = emp.getJoinTime().toInstant();
        if (joinDate.isBefore(instant.minus(20,ChronoUnit.YEARS))) {
            return Optional.of(instant.minus(20, ChronoUnit.YEARS));
        }
        else {
            return Optional.of(joinDate);
        }
    });
}

of course you can replace the inner if-else with ternary conditional expression:

Optional<Instant> getJoinDate(final Instant instant) {
    final Optional<Employee> joinTime = empService.retrieveById(1);
    return joinTime.flatMap (emp -> {
        final Instant joinDate = emp.getJoinTime().toInstant();
        return joinDate.isBefore(instant.minus(20,ChronoUnit.YEARS)) ?
            Optional.of(instant.minus(20, ChronoUnit.YEARS)) :
            Optional.of(joinDate);
    });
}

or even shorter:

Optional<Instant> getJoinDate(final Instant instant) {
    return empService.retrieveById(1).flatMap (emp -> 
            emp.getJoinTime().toInstant().isBefore(instant.minus(20,ChronoUnit.YEARS)) ?
            Optional.of(instant.minus(20, ChronoUnit.YEARS)) :
            Optional.of(emp.getJoinTime().toInstant()));
}

However, this has the disadvantage of calling emp.getJoinTime().toInstant() twice.

Sign up to request clarification or add additional context in comments.

Comments

1

If I understand your code correctly, this is it:

Optional<Instant> getJoinDate(Instant instant) {
    Instant cap = instant.minus(20,ChronoUnit.YEARS)
    return empService.retrieveById(1)
        .map(employee -> employee.getJoinTime().getInstant())
        .map(joinInstant -> joinInstant.before(cap)?cap:joinInstant);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.