Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Returning the top 5values from a hash table

Hey, i want to return the top 5 values from a hash table, where the key is a string and the value is a float, and the top value is the highest float value. I have code to return the max, but im not sure how to get the top 5.

map = readDir(dir,filename, map);
Set set = map.keySet();
Float max = Float.NEGATIVE_INFINITY;
Object key = "";

for(Object o : set)
{
Float val = (Float)map.get(o);
if(val > max)
{
max = val;
key = o;
}


}

System.out.println("Directory " + key + " " + max);

}
Does anybody know how i could do this?
Thanks
[772 byte] By [cupanTae] at [2007-11-11 7:55:40]
# 1 Re: Returning the top 5values from a hash table
Boy, that code looks familiar!

This will sort your floats and look up their associated keys. It makes a new Map and reverses the key-value association. Then it gets all the keys (which are now the Floats), sorts them, and reverses that sort. The print loop prints out all of them. You can of course stop after the first five if that's all you want.
Set keySet = map.keySet();
Float max = Float.NEGATIVE_INFINITY;
Object key = "";

Map invertedMap = new HashMap();

for(Object o : keySet)
{
Float val = (Float)map.get(o);
invertedMap.put(val,o);
}

List floatList = new ArrayList();
floatList.addAll(map.values());
Collections.sort(floatList);
Collections.reverse(floatList);

for(Object o : floatList)
println("f: "+o+" k: "+invertedMap.get(o));
Laszlo at 2007-11-11 22:37:03 >