[Java Program] Get Dates between Dates using Java 8 Predicate Functional Interface



Code Example:
package org.code2care.examples;

import java.time.LocalDate;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class PredicateDateBetweenDays {

    public static void main(String[] args) {

        List dates = List.of(
                LocalDate.of(2023, 10, 10),
                LocalDate.of(2023, 10, 11),
                LocalDate.of(2023, 10, 12),
                LocalDate.of(2023, 10, 13),
                LocalDate.of(2023, 10, 14),
                LocalDate.of(2023, 10, 15)
        );

        LocalDate startDate = LocalDate.of(2023, 10, 10);
        LocalDate endDate = LocalDate.of(2023, 10, 14);

        Predicate isDateInRange = date -> date.isAfter(startDate) && date.isBefore(endDate);

        List filteredDates = dates.stream()
                .filter(isDateInRange)
                .toList();

        System.out.println("Dates between " + startDate + " and " + endDate + ": " + filteredDates);
    }
}


Output:

Dates between 2023-10-10 and 2023-10-14: [2023-10-11, 2023-10-12, 2023-10-13]



Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap