I have a list of sorted dates like this:
2016-07-07
2016-07-08
2016-07-09
2016-07-10
2016-07-11
2016-07-12
2016-07-13
...
2016-07-31
2016-08-01
2016-08-02
2016-08-03
...
2017-01-01
2017-01-02
2017-01-03
...
Map<YearMonth, List<LocalDate>>
Map<YearMonth, List<LocalDate>> d = dates.stream().collect(Collectors.toList())
.stream().collect(Collectors.groupingBy(date -> YearMonth.from(date)));
{2016-12=[2016-12-01, 2016-12-02,...2016-12-31], 2016-11=[2016-11-01, 2016-11-02,...]}
{2016-07=[...], 2016-08=[...]}
{2016-07=[2016-07-01, 2016-07-02, ...], 2016-08=[2016-08-01, 2016-08-02, ...]}
Map<YearMonth, List<LocalDate>> m = stream().collect(Collectors.toList())
.stream().sorted((e1,e2) -> e2.compareTo(e1))
.collect(Collectors.groupingBy(date -> YearMonth.from(date)));
{2016-07=[2016-07-31, 2016-07-30, ...], 2016-08=[2016-08-31, 2016-08-30, ...]}
Use a TreeMap as collector so the output is sorted by key.
Something like this:
dates.stream()
.sorted()
.collect(
Collectors.groupingBy(YearMonth::from, TreeMap::new, Collectors.toList())
);