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:

Share:
23,464
Amer
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, 2022

Comments

  • Amer
    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
    BalusC over 12 years
    Welcome 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
    user1066566 over 12 years
    Yeah,I got it.I will do better.
  • Skynet
    Skynet over 10 years
    If 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
    BalusC over 10 years
    @Pirate: It's sorted on timestamp (as available by Date#getTime()), not on first day of year. Even more, the java.util.Date doesn't have any concept like "first day of year". Your problem is caused elsewhere. Perhaps Date instances used as keys were created the wrong way via java.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
    Skynet over 10 years
    So you mean it is sorted based on the current date?
  • BalusC
    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's 1 Jan 2012, 2 Jan 2012, 1 Jan 2013, 2 Jan 2013.
  • Skynet
    Skynet over 10 years
    Means 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
    Narendra Singh about 7 years
    How to sort it in descending order?
  • BalusC
    BalusC about 7 years