Search code examples
groovytreemap

Get first n elements from sortedmap


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!!


Solution

  • 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 Strings.

    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:

    1. Sort the List keywords based on the value field.
    2. Map<String, Integer> map = new LinkedHashMap<String, Integer>();
    3. Iterate over the first n items in keywords and populate map. Because you are using a LinkedHashMap the entries will stay in the right order.
    4. return map;