我有这个结构:
Map<String, String> map = new HashMap<String, String>();
,数据如下所示:
("10/11/2015", "A")
("10/12/2015", "B")
("10/13/2015", "C")
("10/14/2015", "D")
("10/15/2015", "E")
我想按日期(键)对地图进行排序,所以我尝试将字符串转换为Calendar类型,然后将它们移动到TreeMap中,如下所示:
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Calendar calendar = Calendar.getInstance();
TreeMap<Calendar, String> tree = new TreeMap<Calendar, String>();
for(Map.Entry<String, String> entry : map.entrySet()){
String key = entry.getKey();
String value = entry.getValue();
calendar.setTime(formatter.parse(key));
tree.put(calendar, value);
}
但是当我打印密钥时,结果如下所示:
10/11/2015
10/15/2015
10/14/2015
10/12/2015
10/13/2015
如何正确按日期(字符串类型的日期)对地图进行排序?
答案 0 :(得分:5)
根据您的示例,您最终应该使用TreeMap
一个Calendar
密钥,因为您使用的是Calendar
的相同实例。
相反,如果您为每个条目使用了Calendar
的新实例,例如......
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Map<String, String> map = new HashMap<>();
map.put("10/11/2015", "A");
map.put("10/12/2015", "B");
map.put("10/13/2015", "C");
map.put("10/14/2015", "D");
map.put("10/15/2015", "E");
TreeMap<Calendar, String> tree = new TreeMap<Calendar, String>();
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry);
String key = entry.getKey();
String value = entry.getValue();
Calendar calendar = Calendar.getInstance();
calendar.setTime(formatter.parse(key));
tree.put(calendar, value);
}
for (Calendar key : tree.keySet()) {
System.out.println(key.getTime());
}
它会打印更像......的内容。
Sun Oct 11 00:00:00 EST 2015
Mon Oct 12 00:00:00 EST 2015
Tue Oct 13 00:00:00 EST 2015
Wed Oct 14 00:00:00 EST 2015
Thu Oct 15 00:00:00 EST 2015
如果您使用的是Java 8(+),那么您确实应该使用新的日期/时间API,例如......
Map<LocalDate, String> tree = new TreeMap<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry);
String key = entry.getKey();
String value = entry.getValue();
LocalDate ld = LocalDate.parse(key, DateTimeFormatter.ofPattern("MM/dd/yyyy"));
tree.put(ld, value);
}
for (LocalDate key : tree.keySet()) {
System.out.println(key);
}