按日期对项目进行分组 [英] Grouping items by date

查看:439
本文介绍了按日期对项目进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的列表中有项目,项目有一个字段,显示项目的创建日期。

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.

如果用户选择压缩,我需要将我的项目分组,以便在同一天创建的项目将被分组。在上面的示例中,仅在同一天创建了第1项和第2项。其他人也是团体,但他们只有一个项目,因为当天只创建了一个项目。

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}}

如果用户选择

{{item1, item2, item3, item4}, {item5}, {item6}, {item7}}

如果用户选择

{{item1, item2, item3, item4, item5}, {item6}, {item7}}

如果用户选择

{{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.

如果使用 Map ,我认为按键如下:

In case of usage of Map, I thought as the keys as follow:

day =一年中的某一天

=一年中的一周

=一年中的某个月

=年

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.

推荐答案

我会使用 Collectors.groupingBy 并调整<$ c分类器上的$ c> LocalDate ,以便具有相似日期的项目(根据用户提供的压缩)组合在一起。

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.

为此,首先创建以下地图

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());

注意:对于day,a TemporalAdjuster ,可以使用日期不变。

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))));

LocalDate 是通过以下方式调整的 LocalDate.with(TemporalAdjuster) 方法。

The LocalDate is adjusted by means of the LocalDate.with(TemporalAdjuster) method.

这篇关于按日期对项目进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆