8

I trying to sort this HashMap based on date in keys

My Hash map:

Map<Date, ArrayList> m = new HashMap<Date, ArrayList>();

Amer
  • 1,820
  • 4
  • 17
  • 24
  • 1
    #winces# I'd be careful of attempting to use this in a multi-threaded environment, if you aren't using those `Date`s in an immutable fashion - calling any of that objects `get()` methods actually mutates the values it holds, so the actual value depends on the order of (not only) `set()`s _and_ `get()`s. I'd rather trust the JodaTime library for this... – Clockwork-Muse Nov 28 '11 at 16:49

2 Answers2

33

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:

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • 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? – Skynet Nov 27 '13 at 13:33
  • @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. – BalusC Nov 27 '13 at 13:41
  • So you mean it is sorted based on the current date? – Skynet Nov 27 '13 at 13:47
  • @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`. – BalusC Nov 27 '13 at 14:15
  • 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. – Skynet Nov 28 '13 at 03:43
  • How to sort it in descending order? – Narendra Singh Mar 09 '17 at 11:48
  • @MrNarendra: just use https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#reverseOrder-- – BalusC Mar 10 '17 at 10:09
0

Use TreeMap instead of HashMap to store the data,it will be sorted automatically.

  • 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 http://stackoverflow.com/faq. – BalusC Nov 28 '11 at 16:10
  • Yeah,I got it.I will do better. – user1066566 Dec 07 '11 at 16:27