Java TemporalQuery Lambda method reference vs custom class

Description

Java TemporalQuery Lambda method reference vs custom class

import java.time.LocalDate;
import java.time.Month;
import java.time.Year;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQuery;

class FamilyBirthdays {
  public static Boolean isFamilyBirthday(TemporalAccessor date) {
    int month = date.get(ChronoField.MONTH_OF_YEAR);
    int day = date.get(ChronoField.DAY_OF_MONTH);

    if ((month == Month.APRIL.getValue()) && (day == 3))
      return Boolean.TRUE;

    if ((month == Month.MAY.getValue()) && (day == 29))
      return Boolean.TRUE;

    return Boolean.FALSE;
  }/*from w w w.j ava  2s. c om*/
}

class FamilyVacations implements TemporalQuery<Boolean> {

  public Boolean queryFrom(TemporalAccessor date) {
    int month = date.get(ChronoField.MONTH_OF_YEAR);
    int day = date.get(ChronoField.DAY_OF_MONTH);

    if ((month == Month.APRIL.getValue()) && ((day >= 3) && (day <= 8)))
      return Boolean.TRUE;

    if ((month == Month.AUGUST.getValue()) && ((day >= 8) && (day <= 14)))
      return Boolean.TRUE;

    return Boolean.FALSE;
  }
}

public class Main {

  public static void main(String[] args) {
    Month month = Month.AUGUST;
    int day = 5;

    LocalDate date = LocalDate.of(Year.now().getValue(), month, day);
    Boolean isFamilyVacation = date.query(new FamilyVacations());
    // Invoking the query using a lambda expression.
    Boolean isFamilyBirthday = date.query(FamilyBirthdays::isFamilyBirthday);

    if (isFamilyVacation.booleanValue() || isFamilyBirthday.booleanValue())
      System.out.printf("%s is an important date!%n", date);
    else
      System.out.printf("%s is not an important date.%n", date);
  }
}



PreviousNext

Related