Storing group of objects with Dates in a Map
I have a group of Events that occurred at some Dates. Each event has a Date field. Now I'd like to create a Map where for each Date (taken from all dates of events) I will assign List of Events that occurred on that date. So in pseudocode :
public Map<Date, List<Event>> function(List<Event> list){
Date[]dates = new Date(list.len(开发者_JAVA技巧));
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)
}
}
Is this a proper way of thinking? If yes: how can I create list of events with specific date and then add it to the map? I'm just starting with the collections.
EDIT
So I'm trying to use solution of hisdrewness. The last problem is how to retrieve events with the desired Date. So I'm creating an Iterator over my map but what next ? In python it is easy but how can I 'get objects with date=date' in Java ?
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;
}
If someone else needs something like this, now (Java8+) it can be done, for example, like this (Event property created
is LocalDateTime). TreeMap for examle (if sorting needed). Collectors.toCollection(ArrayList::new))
may be changed to Collectors.toList
(List type not guaranteed).
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))
)
);
Will also work Collectors.groupingBy(event -> event.getCreated().toLocalDate())
but you won't be able to specify the type of Map
Here's how I would code this method:
public Map<Date, List<Event>> function(List<Event> list){
Map<Date, List<Event>> sortedEvents = new HashMap<Date, List<Event>>();
for(Event event : list) {
Date eventDate = event.getDate();
if(!sortedEvent.containsKey(eventDate)) {
sortedEvent.put(eventDate, new ArrayList<Event>());
}
sortedEvent.get(eventDate).add(event);
}
}
or in psuedo code:
Loop through events
Get event date
If Map does not contain member for event date
Create new member for event date
End if
Add event for given event date
End Loop
One important caveat is comparing the dates as hash keys. Things like time zone, millisecond precision, etc. should be considered.
EDIT
For iterating over the return value:
Map<Date, List<Event>> map = // call sort function
for(Map.Entry<Date, List<Event>> entry : map.entrySet()) {
Date date = entry.getKey();
List<Event> events = entry.getValue();
}
You're mostly there. Instead of iterating through the dates, you can iterate through the events, adding each event to the proper "bucket" as you go through.
精彩评论