Quote:
Originally Posted by KWSW
I need to sort out based on frequency certain events that happen.
I use a map with the event name as the key(String) and the frequency(Integer) as the value and every time an event happens.
I have no problems with the part of adding and updating but am abit stuck at the sorting part as I need to display the events sorted from higest frequency to lowest.
At first I was thinking of putting them into another hashmap with the frequency as the key as it auto sorts based on key but if I have 2 or more events with the same frequency, I might overwrite them.
TIA :)
So now you have a Map<String, Integer> where the keys are Strings and the
frequencies are Integers.
Build another map like this: Map<Integer, List<String>> and add your value, key
pairs (frequencies, keys) like this:
-
-
// the 'inverted' map
-
private Map<Integer>, List<String>>= new TreeMap<Integer, List<String>>();
-
...
-
public void add(Integer freq, String key) {
-
List<String> list= map.get(freq);
-
if (list == null) map.put(freq, list= new ArrayList<String>());
-
list.add(key);
-
}
-
That's all there is to it ;-)
kind regards,
Jos