Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter date by even date using streams

Tags:

java

I have written method in Java 9 for getting days from LocalDate.

private static List<LocalDate> getDaysOneDayDifference(LocalDate start, LocalDate end) {
   return start.datesUntil(end).collect(Collectors.toList());
}

Above method prints this result:

[2019-01-25, 2019-01-26, 2019-01-27, 2019-01-28, 2019-01-29, 2019-01-30, 2019-01-31, 2019-02-01, 2019-02-02, 2019-02-03]

How can I create a method or modify above one, to filter those days to display only even days. Should I use regexp or it is possbile to do it much easier.

like image 398
Reddi Avatar asked Jun 08 '26 21:06

Reddi


1 Answers

You can add a filter to it and filter days of which the day of month is even:

private static List<LocalDate> getDaysOneDayDifference(LocalDate start, LocalDate end) {
   return start.datesUntil(end)
               .filter(d -> d.getDayOfMonth() % 2 == 0)
               .collect(Collectors.toList());
}

The getDayOfMonth method returns the day of the month, from 1 to 31.

like image 105
Mark Avatar answered Jun 10 '26 10:06

Mark