How to sort HashMap based on Date?

2019-01-27 21:06发布

I trying to sort this HashMap based on date in keys

My Hash map:

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

2条回答
贼婆χ
2楼-- · 2019-01-27 21:45

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:

查看更多
SAY GOODBYE
3楼-- · 2019-01-27 21:53

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

查看更多
登录 后发表回答