Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort HashMap keys [duplicate]

Tags:

java

hashmap

I have one problem

HashMap<String, List<AppPrjMilestone>> dateMilestoneMap
                                 = new HashMap<String, List<AppPrjMilestone>>();

I am putting dynamic key in Hashmap object like this:

dateMilestoneMap.put(""+crateDate,value);

Finally I am getting result like this:

("28/01/2012",value)
("01/01/2012",value)
("26/01/2012",value)

I want return key value pairs in desc or asc order. How can I do that?

like image 438
Naveen A Avatar asked Jan 28 '12 17:01

Naveen A


1 Answers

HashMaps do not store the sorted order of keys by definition. You can however accomplish this by acquiring an array of the keys via: Object[] keys = map.keySet().toArray(); Then sorting the list with Arrays: Arrays.sort(keys); and finally iterating through each key and retrieving the value from the HashMap.

for(Object key : keys) { System.out.println(map.get(key)); }

The sorting step here will make the algorithm run in O(n lg n) rather than O(n) which would be possible using a sorting data structure.

This will sort the list lexicographically. Since it looks like your question uses the common US date format, this will sort the list by day, then month and finally year. This is not likely correct. You can either use a year, month, day string format of the date, or adopt a more appropriate key object. Joda-Time's DateTime and DateTimeComparator would be quite useful. Simply use DateTime as the key and a DateTimeComparator instance when calling Arrays.sort(keys, comparator);.

like image 75
allingeek Avatar answered Sep 30 '22 03:09

allingeek