如何根据日期对 HashMap 进行排序?
我试图根据键中的日期对这个 HashMap 进行排序
I trying to sort this HashMap based on date in keys
我的哈希图:
Map
推荐答案
使用 TreeMap 而不是 哈希映射.由于 Date 已经实现了 Comparable,插入时会自动排序.
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>();
或者,如果您有一个现有的 HashMap 并希望基于它创建一个 TreeMap,请将其传递给构造函数:
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);
另见:
- Java 教程 - 地图实现
- Java 教程 - 对象排序
相关文章