Sorting a HashMap by date

后端 未结 6 1991
隐瞒了意图╮
隐瞒了意图╮ 2021-02-15 16:00

In a Java class I have a method to reOrder an existing HashMap by date. The HashMap is of a type where the Object contains a field called exp

6条回答
  •  隐瞒了意图╮
    2021-02-15 16:37

    Use a TreeMap instead of HashMap. it will be sorted automatically on insertion.

    Map< Date, Object> m = new TreeMap< Date, Object>();
    

    Alternatively, if you have an existing HashMap and want to create a TreeMap based on it, pass it to the constructor:

    Map< Date, Object> sortedMap = new TreeMap< Date, Object>(m);
    

    Hope it will help you.

提交回复
热议问题