1

I am trying to sort my output of my program based on the number of occurrences of each key in the hashmap. I want it to print out in an increasing order of occurrences. It already prints out correctly, just not in order. I looked at this page Sort a Map<Key, Value> by values but its really confusing on what works still and what doesn't.

Hashmap -

Map<String, NumberHolder> uaCount = new HashMap<String, NumberHolder>();

Printing part

for(String str : uaCount.keySet())
    {
        String [] arr = str.split(":");                     
        long average = uaCount.get(str).sumtime_in_milliseconds / uaCount.get(str).occurrences;         
        System.out.println(arr[0] + " ---> " + arr[1] + "---> " + arr[2] + "--->" + arr[3] +  "\nAverage = "  + average + " milliseconds \nOccurrences = " + uaCount.get(str).occurrences);
    }

My NumberHolder class defined

public static class NumberHolder
{
    public int occurrences = 0;
    public int sumtime_in_milliseconds = 0;     
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
user2007843
  • 609
  • 1
  • 12
  • 30
  • 1
    By the way, if you can add external dependencies then take a look at Google Guava multimaps/multisets. They do the counting bit for you and have nice API for sorting among other things. – vitaly Apr 02 '13 at 14:06

1 Answers1

1

EDIT: misread requirements. See below.

You need to get all the objects outIf you want to keep it the way you have it, do this:

final ArrayList<Map.Entry<String,NumberHolder>> entries 
    = new ArrayList<Map.Entry<String,NumberHolder>>(uaCount.entrySet());

Comparator<Map.Entry<String,NumberHolder>> comp = new Comparator<Map.Entry<String,NumberHolder>>() {
    @Override
    public int compare(Map.Entry<String, Something> o1, Map.Entry<String, Something> o2) {
        return Integer.compare(o1.getValue().occurrences,o2.getValue().occurrences);
    }
};

Collections.sort(entries, comp);

for(Map.Entry<String,NumberHolder> entry : entries)
{
    ... // use entry.getKey(), entry.getValue()
}

Note that the question you referenced does appear to have a lot of useful answers and other information, especially if performance is an issue.

Rob I
  • 5,627
  • 2
  • 21
  • 28
  • 2
    This solution is sorting on keys and the OP needs to sort on "occurence" (i.e. field of the value object). Please fix it. – ben75 Apr 02 '13 at 13:52
  • @ben75 Thanks - I totally misread that. Take a look at my solution now, please. – Rob I Apr 02 '13 at 14:00
  • Minor nitpicking: You should not use subtraction for comparison, as it will blow up when values are near Integer.MAX_VALUE or .MIN_VALUE. – Rainer Schwarze Apr 02 '13 at 14:13