How to sort HashMap based on Date?
23,464
Use a TreeMap
instead of HashMap
. As Date
already implements Comparable
, it will be sorted automatically on insertion.
Map<Date, ArrayList> m = new TreeMap<Date, ArrayList>();
Alternatively, if you have an existing HashMap
and want to create a TreeMap
based on it, pass it to the constructor:
Map<Date, ArrayList> sortedMap = new TreeMap<Date, ArrayList>(m);
See also:
Author by
Amer
I help teams adopt DevOps culture, embrace automation and improve development workflow. Rescuing failing projects by breaking down silos, ensuring collaboration, bringing the business goals into focus, and minimizing the overhead of development processes.
Updated on July 09, 2022Comments
-
Amer almost 2 years
I trying to sort this HashMap based on date in keys
My Hash map:
Map<Date, ArrayList> m = new HashMap<Date, ArrayList>();
-
BalusC over 12 yearsWelcome at Stack Overflow! Just curious, why are you repeating an already given answer? This isn't kind of a "discussion forum" where folks usually confirm the answer by repeating it more or something. Here on a Q&A site you just vote it up or post a better answer. See also stackoverflow.com/faq.
-
user1066566 over 12 yearsYeah,I got it.I will do better.
-
Skynet over 10 yearsIf I am implementing Sort on dates, the above method will sort them based on first day of the year. While I want a sort based on the current date, I will have to implement a comparator. Any heading?
-
BalusC over 10 years@Pirate: It's sorted on timestamp (as available by
Date#getTime()
), not on first day of year. Even more, thejava.util.Date
doesn't have any concept like "first day of year". Your problem is caused elsewhere. PerhapsDate
instances used as keys were created the wrong way viajava.util.Calendar
which indeed has a concept of "first day of year". Just press "Ask Question" button on right top along with an SSCCE in order to be able to get answers on that. -
Skynet over 10 yearsSo you mean it is sorted based on the current date?
-
BalusC over 10 years@Pirate: It's sorted on timestamp, not on first day of year as you implied. So it's not e.g.
1 Jan 2012, 1 Jan 2013, 2 Jan 2012, 2 Jan 2013
, but it's1 Jan 2012, 2 Jan 2012, 1 Jan 2013, 2 Jan 2013
. -
Skynet over 10 yearsMeans I do not have to implement a comparetor, however as these date values are stored as keys, do they need to be unique? I am about to find this all out, writing a SSCCE.
-
Narendra Singh about 7 yearsHow to sort it in descending order?
-
BalusC about 7 years@MrNarendra: just use docs.oracle.com/javase/8/docs/api/java/util/…