【发布时间】:2011-05-18 03:27:17
【问题描述】:
我有一个特定对象(会议)的列表,我需要使用字段属性(java.util.Date)对其进行分组,并将它们放在另一个对象中,该对象是属于同一月份的分组会议类型对象的容器/年。
所以我正在考虑一些代码,它接收从数据库中获取的会议列表,然后在特定的 MonthMeetings 对象中按月/年对它们进行分组,为此我有一个使用 Map 的代码,例如:
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;
}
我相信,这段代码解决了问题的第一部分,将会议按其特定的 MonthMeetings 对象分组。现在我期待按 MonthMeetings 特定的月/年值对这张地图进行排序。我可能会尝试在 MonthMeetings 对象上实现可比较,但问题来了:
当地图是对象时,如何根据它的值而不是键对地图进行排序?
对此有何建议?
提前发送。
【问题讨论】:
标签: java sorting collections map