Java Reference
In-Depth Information
Under a wide variety of circumstances we may find ourselves wanting to answer a
question about a particular temporal object. Some example questions we may want
answers to are:
• Is the date before March 1st?
• Is the date in a leap year?
• How many days is it from today until my next birthday?
This is acheived by the use of the TemporalQuery interface, which is defined like
public interface TemporalQuery < R > {
R queryFrom ( TemporalAccessor temporal );
The parameter to queryFrom() should not be null, but if the result indicates that a
value was not found, null could be used as a return value.
The Predicate interface can be thought of as a query that can
only represent answers to yes-or-no questions. Temporal
queries are more general and can return a value of “How
many?” or “Which?” instead of just “yes” or “no.”
Let's look at an example of a query in action, by considering a query that answers
the following question: “Which quarter of the year is this date in?” Java 8 does not
support the concept of a quarter directly. Instead, code like this is used:
LocalDate today = LocalDate . now ();
Month currentMonth = today . getMonth ();
Month firstMonthofQuarter = currentMonth . firstMonthOfQuarter ();
This still doesn't give quarter as a separate abstraction and instead special case code
is still needed. So let's slightly extend the JDK support by defining this enum type:
public enum Quarter {
Now, the query can be written as:
public class QuarterOfYearQuery implements TemporalQuery < Quarter > {
public Quarter queryFrom ( TemporalAccessor temporal ) {
LocalDate now = LocalDate . from ( temporal );
if ( now . isBefore ( now . with ( Month . APRIL ). withDayOfMonth ( 1 ))) {
return Quarter . FIRST ;
} else if ( now . isBefore ( now . with ( Month . JULY )
Search WWH ::

Custom Search