title: In Java, I need to group the keys of a hash map based on the basis of their values
body: <p>I need to find the topN keys.</p>
  
  <p>I have an input as a HashMap in the form as (key : value):</p>
  
  <pre><code>Banana : 13  
  Apple: 12  
  Mango : 32  
  Orange : 12  
  Grape : 18  
  Pear : 12  
  Peach : 18  
  </code></pre>
  
  <p>I created a linked HapMap that is sorted based on values:</p>
  
  <pre><code>private static &lt;K extends Comparable, V extends Comparable&gt; Map&lt;K, V&gt; sortByValues(Map&lt;K, V&gt; map) {
      List&lt;Map.Entry&lt;K, V&gt;&gt; entries = new LinkedList&lt;Map.Entry&lt;K, V&gt;&gt;(map.entrySet());
  
      Collections.sort(entries, new Comparator&lt;Map.Entry&lt;K, V&gt;&gt;() {
  
          @Override
          public int compare(Map.Entry&lt;K, V&gt; o1, Map.Entry&lt;K, V&gt; o2) {
              return o2.getValue().compareTo(o1.getValue());
          }
      });
      Map&lt;K, V&gt; sortedMap = new LinkedHashMap&lt;K, V&gt;();
      for (Map.Entry&lt;K, V&gt; entry : entries) {
          sortedMap.put(entry.getKey(), entry.getValue());
      }
      return sortedMap;
  }
  </code></pre>
  
  <p>this gave my the output as:</p>
  
  <pre><code>Mango : 32  
  Grape : 18  
  Peach : 18  
  Banana : 13  
  Apple: 12  
  Orange : 12  
  Pear : 12  
  </code></pre>
  
  <p>Now if I want to the Top-4 fruits, how should I approach if I want the output to be:</p>
  
  <pre><code>Mango :32  
  Grape, Peach : 18  
  Banana :13  
  Apple, Orange, Pear: 12  
  </code></pre>
  
  <p>I tried iterating through the sorted hashMap and compared the values of subsequent elements by doing</p>
  
  <pre><code>int sizeOfMap = myValueSortedMap.size();
  ArrayList&lt;String&gt; keyArr = new ArrayList&lt;String&gt;();
  int cnt=0,keyVal=0;
  
  while(cnt&lt;(sizeOfMap-1)){
  
      if(myValueSortedMap.values().toArray()[cnt] == myValueSortedMap.values().toArray()[cnt+1]){
  
          keyArr.add((String) myValueSortedMap.keySet().toArray()[cnt]+ " , " +(String) myValueSortedMap.keySet().toArray()[cnt+1]);
      }
      else{
          keyArr.add((String) myValueSortedMap.keySet().toArray()[cnt]);
          keyVal = (int) myValueSortedMap.values().toArray()[cnt];
      }
      cnt++;
  }
  </code></pre>
  
  <p>but this does not always work.</p>
  
  <p>I am not able to think of a way around this. Could someone please give me a lead?</p>