This is the solution we came up with. The parseTimeStamps
method takes the list of timeStamps
iterates over it, and uses a Calendar
object to set the hours, minutes, seconds, and milliseconds to 0, thereby giving us just the day. We then check our groupedUserLogins
HashMap to see if it contains a key with that date. If it doesn't, we create a key with that day, and a new list of Date objects as the value associated with that key. Subsequently, we add the timestamp(ts
) to the list associated with that day.
In the next iteration, if we come across a key in our HashMap which matches our stripped Calender object, we immediately add that timestamp (ts
) to the list associated with that existing day.
I created the following method, which returns a HashMap> where the key is a Date object and the value is a List of Date Objects. The method accepts a List of timeStamps and groups them by day. It then returns those grouped timestamps in the aforementioned HashMap construct.
public class GroupDatesByDay {
HashMap<Date, List<Date>> groupedUserLogins = new HashMap<Date, List<Date>>();
Calendar cal = Calendar.getInstance();
public HashMap<Date, List<Date>> parseTimeStamps(List<Date> timeStamps) {
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS", Locale.US);
List<Date> timeStamps = new ArrayList<Date>();
for (Date ts : timeStamps) {
cal.setTime(ts);
cal.set(cal.HOUR_OF_DAY, 0);
cal.set(cal.MINUTE, 0);
cal.set(cal.SECOND, 0);
cal.set(cal.MILLISECOND, 0);
if (!groupedUserLogins.containsKey(cal.getTime())) {
groupedUserLogins.put(cal.getTime(), new ArrayList<Date>());
}
groupedUserLogins.get(cal.getTime()).add(ts);
}
keySet = groupedUserLogins.keySet();
keyList.addAll(keySet);
return groupedUserLogins;
}
}
We end up with groupedUserLogins
which has now conveniently stored all unique days as keys pointing to a List which holds our timestamps, as Date
objects. The biggest advantage of this data-structure is that the keys, as well as the values are still Date
objects, giving us future flexibility.
Please feel free to provide alternate solutions, or improve upon what I have presented.