Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort HashMap based on Date? [duplicate]

I trying to sort this HashMap based on date in keys

My Hash map:

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

like image 942
Amer Avatar asked Nov 28 '11 15:11

Amer


1 Answers

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:

  • Java tutorials - Map implementations
  • Java tutorials - Object ordering
like image 173
BalusC Avatar answered Sep 24 '22 08:09

BalusC