Skip to main content

Stream 안에서 날짜(LocalDate 등) 비교

List 에 담긴 데이터

List<LocalDate> dates = List.of(
    LocalDate.of(2023, 5, 1),
    LocalDate.of(2024, 12, 25),
    LocalDate.of(2025, 7, 21)
);

1. 특정 날짜보다 이전/이후인 것만 필터

LocalDate today = LocalDate.now();

List<LocalDate> futureDates = dates.stream()
    .filter(date -> date.isAfter(today))
    .collect(Collectors.toList());
  • isAfter(), isBefore() 메서드

2. 가장 이른 날짜/늦은 날짜 찾기 (최솟값/최댓값)

Optional<LocalDate> earliest = dates.stream()
    .min(Comparator.naturalOrder());
Optional<LocalDate> latest = dates.stream()
    .max(Comparator.naturalOrder());
  • min(), max() 메서드

3. Stream 두 개의 날짜끼리 비교 (예: 한 쌍씩 비교)

다음은 두 날짜 리스트의 각 요소끼리 비교하는 메서드이다.

List<LocalDate> list1 = List.of(LocalDate.of(2024, 1, 1), LocalDate.of(2025, 1, 1));
List<LocalDate> list2 = List.of(LocalDate.of(2023, 12, 31), LocalDate.of(2026, 1, 1));

IntStream.range(0, Math.min(list1.size(), list2.size()))
    .mapToObj(i -> list1.get(i).isAfter(list2.get(i)))
    .forEach(System.out::println); // true, false

4. 객체 리스트의 날짜 필드 비교

  • 코드 설명: 오늘 이후 열릴 이벤트만 뽑기
  • 핵심 메서드: isAfter(LocalDate.now())
  • Stream 기능 사용: filter, collect
class Event {
    String name;
    LocalDate date;
    public Event(String name, LocalDate date) {
        this.name = name;
        this.date = date;
    }
    public LocalDate getDate() { return date; }
}

List<Event> events = List.of(
    new Event("A", LocalDate.of(2025, 5, 5)),
    new Event("B", LocalDate.of(2023, 1, 1))
);

List<Event> upcoming = events.stream()
    .filter(e -> e.getDate().isAfter(LocalDate.now()))
    .collect(Collectors.toList());
  • Event 클래스는 이름(name)과 날짜(date)를 가지는 간단한 클래스이다.
  • getDate() 메서드를 통해 날짜에 접근할 수 있게 해준다.
  • List.of(...)로 두 개의 이벤를 생성한다.
    • "A"는 2025년 5월 5일
    • "B"는 2023년 1월 1일
  • 오늘 날짜가 2025년 7월 21일이므로 upcoming 은 빈 리스트가 된다.

코드

설명

events.stream()

리스트를 스트림으로 변환

.filter(e -> e.getDate().isAfter(LocalDate.now()))

각 이벤트 e 에 대해, 날짜가 오늘 이후인지 검사

.collect(Collectors.toList())

조건을 만족하는 이벤트들을 다시 List로 수집