Click to See Complete Forum and Search --> : Sorting a hash map


Rabbit3cat
03-02-2006, 11:45 AM
I have a hashmap with strings as keys, and float values as values, like below:
{"anne=0.23453, barry=1.254339,steven=0.12449... }

what i want to do is sort this hashmap according to the float values, returning the highest float value first. What i am currently doing is, swapping the keys with the values, so that the floats are the keys, and sorting them with a hashmap:


Set set = map1.keySet();
Map invertedMap = new HashMap();

for(Object o : set)
{
float val = (Float)map1.get(o);

invertedMap.put(val, o);


}

TreeMap sorted = new TreeMap(Collections.reverseOrder());
sorted.putAll(map1);
Set set1 = sorted.keySet();
Iterator it = set1.iterator();


while(it.hasNext()) {
Object o = it.next();

System.out.println( o + " " + map1.get(o));

}

}



The problem here is that in the hash tables there a few floats are the same value, ie henry=1.6743, and mary=1.6743
so when i invert the hash table, making 1.6743 one of these is ignored. Can anbody think of a way i can do this?
Id appreciate any help
Thanks