java - How to sort map by calendar in string type? -
i have structure:
map<string, string> map = new hashmap<string, string>();
and data looks this:
("10/11/2015", "a") ("10/12/2015", "b") ("10/13/2015", "c") ("10/14/2015", "d") ("10/15/2015", "e")
i want sort map date (key), attempt convert string calendar type , move them treemap below:
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 print key, result looks below:
10/11/2015 10/15/2015 10/14/2015 10/12/2015 10/13/2015
what should sort map date (date in string type) correctly?
based on example, should end treemap
single calendar
key, because you're using same instance of calendar
.
instead, if used new instance of calendar
each entry, example...
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>(); (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); } (calendar key : tree.keyset()) { system.out.println(key.gettime()); }
it print 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(+), should using new date/time api, example...
map<localdate, string> tree = new treemap<>(); (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); } (localdate key : tree.keyset()) { system.out.println(key); }
Comments
Post a Comment