[英]How to sort map by calendar in string type?
I have this structure: 我有这个结构:
Map<String, String> map = new HashMap<String, String>();
and data looks like this: 数据看起来像这样:
("10/11/2015", "A")
("10/12/2015", "B")
("10/13/2015", "C")
("10/14/2015", "D")
("10/15/2015", "E")
I want to sort the map by date (key), so my attempt was to convert the string to Calendar type and then move them into TreeMap like below: 我想按日期(键)对地图进行排序,所以我的尝试是将字符串转换为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);
}
But when I print the key, the result looks like below: 但是当我打印密钥时,结果如下所示:
10/11/2015
10/15/2015
10/14/2015
10/12/2015
10/13/2015
What should I do to sort the map by date (date in String type) correctly? 我该怎么做才能按日期正确排序地图(日期为String类型)?
Based on your example, you should end up with a TreeMap
with a single Calendar
key, because you're using the same instance of Calendar
. 根据您的示例,您应该最终得到一个带有单个
Calendar
键的TreeMap
,因为您使用的是Calendar
的相同实例。
Instead, if you used a new instance of Calendar
for each entry, for example... 相反,如果您为每个条目使用
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());
}
It would print something more like... 它会打印更像...
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
If you're using Java 8(+), then you really should be using the new Date/Time API, for example... 如果您使用的是Java 8(+),那么您确实应该使用新的Date / Time 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.