我需要从每个提到的月份的给定日期数组中提取最少的日期。
示例-日期格式为dd / MM / yyyy以下是示例输入
04/11/2019, 11/11/2019, 18/11/2019, 25/11/2019, 02/12/2019, 09/12/2019,
06/01/2020, 03/02/2020, 10/02/2020, 17/02/2020, 24/02/2020, 02/03/2020,
09/03/2020, 16/03/2020, 23/03/2020, 30/03/2020, 06/04/2020, 13/04/2020,
20/04/2020, 27/04/2020
Run Code Online (Sandbox Code Playgroud)
我需要从每个月获取最少的日期:
输出像-
04/11/2019, 02/12/2019, 06/01/2020, 03/02/2020, 02/03/2020, 06/04/2020
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
如果您使用的是Java-8,则可以使用:
List<LocalDate> collect = Stream.of(strings)
.map(s -> LocalDate.parse(s, format)) // convert your strings to LocalDate
.collect(Collectors.groupingBy(YearMonth::from)) // group by year and month
.values().stream()
.map(a -> a.stream().sorted().limit(1).findFirst().get())
.sorted()
.collect(Collectors.toList()); // collect the results
Run Code Online (Sandbox Code Playgroud)
输出
[2019-11-04, 2019-12-02, 2020-01-06, 2020-02-03, 2020-03-02, 2020-04-06]
Run Code Online (Sandbox Code Playgroud)
public List<LocalDate> filterDates(List<LocalDate> dates) {
return dates.stream()
.collect(Collectors.groupingBy(YearMonth::from))
.values()
.stream()
.map(Collections::min) // .map(Collections::max)
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
.map(Collections::min)您可以使用以下内容代替:
.map(list -> {
list.sort(Comparator.naturalOrder());
return list.get(0);
})
Run Code Online (Sandbox Code Playgroud)
或者:
.map(list -> list.stream().max(Comparator.naturalOrder()))
Run Code Online (Sandbox Code Playgroud)