I've tried to store frequencies of string in a TreeMap so that I can get the most frequently used strings of, say, a specific user. Now what I want to do is to write a method to return me the first n items(top frequently used) from the sorted map.
public TreeMap<String,Integer> getKeywords(int n){
//Can check if sorted for efficiency!
println keywords.size();
keywords=keywords.sort{a,b->
//sort the map desc by value
b.value <=> a.value;
}
TreeMap<String,Integer> result=new TreeMap<>();
//need to fill result with first n elements from keywords
return result;
}
I've tried several ways like using .each()
on keywords or iterate through its keySet, yet none preserves its original order, and I ended up getting result unsorted.
Help & hints are appreciated!!
I don't know Groovy, so I can only comment on Java.
A TreeMap
keeps the entries sorted by the keys, not the values. In your case it's using the natural order of String
s.
If you want a Map
to maintain the order of insertion, use a LinkedHashMap
. If you do this you will need to change the return type to Map<String, Integer>
.
I can't write detailed code as I am unclear about the types of some of your variables, but the basic steps are:
List
keywords
based on the value
field.Map<String, Integer> map = new LinkedHashMap<String, Integer>();
n
items in keywords
and populate map
. Because you are using a LinkedHashMap
the entries will stay in the right order.return map;