views:

39

answers:

2

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

    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;
}
A: 

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.

oksayt
+1  A: 

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.

hisdrewness