I have a list of specific objects(meetings) which I need to group using a field attribute(java.util.Date) and place them in another Object which is a container for grouped meetings type objects belonging to the same month/year.
So I am thinking about some code which receives a meetings list fetched from Database and than group them by month/year in specific MonthMeetings objects, for this I have a code using a Map like:
public static Map<String, MonthMeetings> groupMeetingsByMonth(
List<Meeting> meetings) {
// this is by default sorted by keys I'd like to have it sorted by using
// comparator on MonthMeetings objects, sorted by map values instead of
// keys like SortedMap default impl.
SortedMap<String, MonthMeetings> listMeetingsGroupedByMonth = new TreeMap<String, MonthMeetings>();
String labelMonthYear = "";
// reference to put in map.
MonthMeetings monthMeetings = null;
for (Iterator iterator = meetings.iterator(); iterator.hasNext();) {
// grab a meeting from list
Meeting meeting = (Meeting) iterator.next();
// get meeting date
Date dMeeting = meeting.getScheduledDate();
GregorianCalendar gCalendar = new GregorianCalendar();
gCalendar.setTime(dMeeting);
// simple method that build label in format MM_yyyy to use as map
// key.
labelMonthYear = generatesLabelMonthYear(gCalendar);
// check if MonthMeetings for specific month/year already exists in
// Map
monthMeetings = (MonthMeetings) listMeetingsGroupedByMonth
.get(labelMonthYear);
if (monthMeetings == null) {
// if not create MonthMeetings and add first meeting to it
monthMeetings = new MonthMeetings();
monthMeetings.addMeeting(meeting);
listMeetingsGroupedByMonth.put(labelMonthYear, monthMeetings);
} else {
// if does exist just add another meeting to it
monthMeetings.addMeeting(meeting);
}
}
return listMeetingsGroupedByMonth;
}
This piece of code, I believe, solves the first part of the problem, grouping meetings on its specific MonthMeetings objects. Now I am looking forward to sort this map by MonthMeetings specific month/year values. I am probably going to try implementing comparable on MonthMeetings objects, but than came the question:
How to sort a map based on it’s values, not keys, when these are objects?
Any suggestions on this?
tx in advance.
Create a
TreeSet<MonthMeeting>and add all the values like this:Now it’s sorted on values.
MyComparatorwill be something like: