-2

I have a list of Object Person, which has a dateOfBirth. I want to find the maximum dateOfBirth from the list which is smaller than or equal to some other date using Java 8 streams API. Below is my code using standard for-each loop.

import java.time.LocalDate;

public class Person {
    LocalDate dateOfBirth;

    public LocalDate getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(LocalDate dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
}


//Driver Class
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Person> persons = getPersonList();
        LocalDate myDob = LocalDate.of(2022, 9, 30);
        LocalDate maxDate = null;
        for(Person p : persons) {
            if(p.getDateOfBirth().compareTo(myDob) <= 0) {
                if(maxDate == null || maxDate.compareTo(p.getDateOfBirth()) <= 0) {
                    maxDate = p.getDateOfBirth();
                }
            }
        }
        System.out.println(maxDate);
    }

    private static List<Person> getPersonList() {
        List<Person> persons = new ArrayList<>();
        Person p1 = new Person();
        p1.setDateOfBirth(LocalDate.now());

        Person p2 = new Person();
        p2.setDateOfBirth(LocalDate.of(2022, 9, 29));

        Person p3 = new Person();
        p3.setDateOfBirth(LocalDate.of(2022, 9, 12));

        Person p4 = new Person();
        p4.setDateOfBirth(LocalDate.of(2022, 10, 29));

        persons.add(p1);
        persons.add(p2);
        persons.add(p3);
        persons.add(p4);

        return persons;
    }
}

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Pushpak
  • 147
  • 8

1 Answers1

3
Optional<LocalDate> result = persons.stream()
        .map(Person::getDateOfBirth)
        .filter(date -> !myDob.isBefore(date)) // so date <= myDob
        .max(Comparator.naturalOrder());
Rob Spoor
  • 6,186
  • 1
  • 19
  • 20