gpt4 book ai didi

java - 在 map 中存储带有日期的对象组

转载 作者:太空宇宙 更新时间:2023-11-04 08:47:38 25 4
gpt4 key购买 nike

我有一组在某些日期发生的事件。每个事件都有一个日期字段。现在我想创建一个 map ,其中对于每个日期(取自事件的所有日期),我将分配该日期发生的事件列表。所以在伪代码中:

public Map<Date, List<Event>> function(List<Event> list){

Date[]dates = new Date(list.len());

for(Object o: list)
add o.date to dates

for(int i=0; i<dates.length; i++){
create list of events with date=dates[i] (using some getDate())
add to map(dates[i], list)
}

}

这是正确的思维方式吗?如果是:如何创建具有特定日期的事件列表,然后将其添加到 map 中?我刚刚从 Collection 开始。

编辑

所以我正在尝试使用他的昏迷解决方案。最后一个问题是如何检索具有所需日期的事件。所以我正在我的 map 上创建一个迭代器,但接下来该怎么办?在 python 中这很容易,但是如何在 Java 中“获取带有 date=date 的对象”?

private String getItems(Date date){
String ret = "";
// DatesSortedMap is my previously built map and it works properly
Iterator i = this.DatesSortedMap.entrySet().iterator();

while( i.hasNext() ){
//how I can get to the object while having iterator ?
if(object.date = date)
ret += object;
}

return ret;
}

最佳答案

如果其他人需要这样的东西,现在(Java8+)可以这样做,例如,像这样(事件属性created是LocalDateTime)。例如 TreeMap(如果需要排序)。 Collectors.toCollection(ArrayList::new)) 可能会更改为 Collectors.toList (不保证列表类型)。

List<Event> events ...

Map<LocalDate, List<Event>> = events.stream().collect(
Collectors.groupingBy(
event -> event.getCreated().toLocalDate(),
TreeMap::new,
Collectors.mapping(event -> event, Collectors.toCollection(ArrayList::new))
)
);

也可以使用Collectors.groupingBy(event -> event.getCreated().toLocalDate()),但您无法指定Map的类型

关于java - 在 map 中存储带有日期的对象组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4011673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com