How to sort HashMap based on Date? [duplicate]

若如初见. 提交于 2019-11-28 07:24:27

问题


This question already has an answer here:

  • Sorting hashmap based on keys 8 answers

I trying to sort this HashMap based on date in keys

My Hash map:

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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/8298290/how-to-sort-hashmap-based-on-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!