Skip to content

Commit a0df5e5

Browse files
authored
add using collection.max (#17864)
1 parent f476af1 commit a0df5e5

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/maxdate/DateHelper.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package com.baeldung.streams.maxdate;
22

33
import java.time.LocalDate;
4+
import java.util.Collections;
45
import java.util.Comparator;
56
import java.util.Date;
67
import java.util.List;
8+
import java.util.stream.Collectors;
79

810
public class DateHelper {
911

@@ -87,4 +89,21 @@ static final LocalDate findMinDateOfLocalEventsWithComparator(List<LocalEvent> e
8789
.get();
8890
}
8991

92+
static Date findMaxDateWithCollections(List<Event> events) {
93+
if (events == null || events.isEmpty()) {
94+
return null;
95+
}
96+
return Collections.max(events.stream()
97+
.map(Event::getDate)
98+
.collect(Collectors.toList()));
99+
}
100+
101+
static LocalDate findMaxLocalDateWithCollections(List<LocalEvent> events) {
102+
if (events == null || events.isEmpty()) {
103+
return null;
104+
}
105+
return Collections.max(events.stream()
106+
.map(LocalEvent::getDate)
107+
.collect(Collectors.toList()));
108+
}
90109
}

core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/maxdate/DateHelperUnitTest.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,5 +186,13 @@ void givenLocalEventList_whenFindMinDateOfLocalEventsWithComparator_thenReturnMa
186186
assertEquals(TODAY_LOCAL, DateHelper.findMinDateOfLocalEventsWithComparator(List.of(TODAY_LOCAL_EVENT, TOMORROW_LOCAL_EVENT, NEXT_WEEK_LOCAL_EVENT)));
187187
}
188188

189-
189+
@Test
190+
void givenEventList_whenFindMaxDateWithCollections_thenReturnMaxDate() {
191+
assertEquals(NEXT_WEEK, DateHelper.findMaxDateWithCollections(List.of(TODAYS_EVENT, TOMORROWS_EVENT, NEXT_WEEK_EVENT)));
192+
}
193+
194+
@Test
195+
void givenLocalEventList_whenFindMaxLocalDateWithCollections_thenReturnMaxDate() {
196+
assertEquals(NEXT_WEEK_LOCAL, DateHelper.findMaxLocalDateWithCollections(List.of(TODAY_LOCAL_EVENT, TOMORROW_LOCAL_EVENT, NEXT_WEEK_LOCAL_EVENT)));
197+
}
190198
}

0 commit comments

Comments
 (0)