Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a HashMap by date

In a Java class I have a method to reOrder an existing HashMap by date. The HashMap is of a type <String, Object> where the Object contains a field called expPayDate and the key string is a sequential number turned into a string.. So I need to loop through the items in the sourceMap and find the item with the newest date then copy it to a tempMap in the correct order. My issue is what is the best way to determine the item with the newest date.

like image 770
Bill F Avatar asked Sep 08 '15 17:09

Bill F


2 Answers

Your best bet will be to use a SortedMap with the Comparator interface.

Here is an example:

public SortedMap<String, Object> getSortedMap(Map<String, Object> originalMap) {
    SortedMap<String, Object> tmpMap = new TreeMap<String, Object>(new Comparator<String>(){
        @Override
        public int compare(String key1, String key2) {
            //logic for comparing dates
        }           
    });
    tmpMap.putAll(originalMap);
    return tmpMap;
}
like image 198
patstuart Avatar answered Sep 19 '22 06:09

patstuart


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.

like image 42
Harish Kumar Avatar answered Sep 23 '22 06:09

Harish Kumar