I have getOffseSeconds method:

private int getOffsetSeconds(LocalDateTime localDateTime, ZoneId zoneId) {
    return ZonedDateTime.of(localDateTime, zoneId).getOffset().getTotalSeconds();

This method is used in shifted LocalDateTime calculation

private void shiftEventDateTimeToOriginalZone(EventDto event) {
            getOffsetSeconds(event.getStartDateTime(), event.getStartDateTimeZone())));
            getOffsetSeconds(event.getEndDateTime(), event.getEndDateTimeZone())));

Now I need similar method to last one but with small change:

private void shiftEventDateTimeToDefaultZone(EventDto event) {
            getOffsetSeconds(event.getStartDateTime(), event.getStartDateTimeZone())));
            getOffsetSeconds(event.getEndDateTime(), event.getEndDateTimeZone())));

As you can see, the difference is in using methods: plusSeconds and minusSeconds. I want replace 2 last methods with another one with same first parameter and second should be lambda operation plusSecondsOperation or minusSecondsOperations. But I do not know how to do it in Java (Java 8).


1 Answer 1


You can add an argument of type:

BiFunction<LocalDateTime, Integer, LocalDateTime>

To your function that will reflect your need: LocalDateTime (initial date), offset, LocalDateTime (date that will be returned after applying the function). The method will look like this:

private void shiftEventDateTime(EventDto event, BiFunction<LocalDateTime, Integer, LocalDateTime> f){}

To apply the function inside the method you can write it this way:

f.apply(event.getStartDateTime(), getOffsetSeconds(event.getStartDateTime(), event.getStartDateTimeZone()));
f.apply(event.getEndDateTime(), getOffsetSeconds(event.getEndDateTime(), event.getEndDateTimeZone()));

And when you invoke your method you need to specify the operation itself:

shiftEventDateTime(event, LocalDateTime::minusSeconds);
shiftEventDateTime(event, LocalDateTime::plusSeconds);

You can choose whatever name for the BiFunction that you like and the one that fits your case the most.


Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.