Grouping items by date(按日期分组项目)
问题描述
I have items in my list and the items have a field, which shows the creation date of the item.
and I need to group them based on a "compression", which the user gives. The options are Day
, Week
, Month
and Year
.
If the user selects day
compression, I need to group my items as such that the items, which are created in the same day, will be groupped. In my example above, only item 1 and item 2 are created in the same day. The others are also groups but they will have only one item because at their day, only one item is created.
{{item1, item2}, {item3}, {item4}, {item5}, {item6}, {item7}}
If the user selects week
:
{{item1, item2, item3, item4}, {item5}, {item6}, {item7}}
If the user selects month
:
{{item1, item2, item3, item4, item5}, {item6}, {item7}}
If the user selects year
:
{{item1, item2, item3, item4, item5, item6}, {item7}}
After groups are created, the date of the items are not important. I mean the key can be anything, as long as the groups are created.
In case of usage of Map
, I thought as the keys as follow:
day
= day of the year
week
= week of the year
month
= month of the year
year
= year
What would be the best solution to this problem? I could not even start it an I cannot think of a solution other than iteration.
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.
这篇关于按日期分组项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按日期分组项目
基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01