Sorting a HashMap by date

后端 未结 6 2007
隐瞒了意图╮
隐瞒了意图╮ 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:32

    If you just need the minimum or maximum date, a simple for each loop might be sufficient:

    Date maxDate = null;
    for (Entry item: hashMap.entrySet()) 
        if (maxDate == null || maxDate before((Date)item.getValue())) 
            maxDate = (Date)item.getValue();
    

    This way complexity is only O(n) and insert and delete operations are cheaper than using a sortedMap. Anyway, I think patstuart's suggestion (using a sortedMap) is more elegant.

提交回复
热议问题