更新时间:2023-01-08 15:58:59
I would use Collectors.groupingBy
with an adjusted LocalDate
on the classifier, so that items with similar dates (according to the compression given by the user) are grouped together.
For this, first create the following Map
:
static final Map<String, TemporalAdjuster> ADJUSTERS = new HashMap<>();
ADJUSTERS.put("day", TemporalAdjusters.ofDateAdjuster(d -> d)); // identity
ADJUSTERS.put("week", TemporalAdjusters.previousOrSame(DayOfWeek.of(1)));
ADJUSTERS.put("month", TemporalAdjusters.firstDayOfMonth());
ADJUSTERS.put("year", TemporalAdjusters.firstDayOfYear());
Note: for "day"
, a TemporalAdjuster
that lets the date untouched is being used.
Next, use the compression
given by the user to dynamically select how to group your list of items:
Map<LocalDate, List<Item>> result = list.stream()
.collect(Collectors.groupingBy(item -> item.getCreationDate()
.with(ADJUSTERS.get(compression))));
The LocalDate
is adjusted by means of the LocalDate.with(TemporalAdjuster)
method.