Note that there are some explanatory texts on larger screens.

plurals
  1. POPrinting a sorted treemap(sorted based on values)
    text
    copied!<p>I have a sorted a TreeMap based on values, and it's printed as shown:</p> <pre><code>abortion-2 able-2 ab-2 aaron-2 aaa-2 aa-2 a-2 absent-1 absence-1 abraham-1 ability-1 aberdeen-1 abc-1 </code></pre> <p>But it seems like the words with same values are being printed in the reverse sorted order:</p> <p><em><strong>"abortion, able, ab, aaron, aaa, aa, a"</em></strong> instead of <strong><em>"a, aa, aaa, aaron, ab, able abortion"</em></strong> and so on. </p> <p>I have even thought of adding each set of keys having same value to the TreeSet and print it out, but I couldn't iterate it based on next values.</p> <p>Here is the comparator that I'm passing on to the TreeMap. Can anybody help me correcting the code to print it in the correct order? </p> <pre><code> public class MyComparator implements Comparator&lt;String&gt;{ Map&lt;String, Integer&gt; tiedMap; public MyComparator(Map&lt;String, Integer&gt; map){ this.tiedMap = map; } public int compare(String a, String b){ if(tiedMap.get(a)&gt;=tiedMap.get(b)){ return -1; } else return 1; } } </code></pre> <p>And here is how I'm trying to print it:</p> <pre><code>Iterator it = tree.entrySet().iterator(); for(int i=0; i&lt;n; i++){ if(it.hasNext()){ Map.Entry pairs = (Map.Entry)it.next(); System.out.println(pairs.getKey()+"-"+pairs.getValue()); } } </code></pre> <p>Edit: I'm reading the input into a TreeMap, and then passing it to another TreeMap.</p> <p>Edit: Code that creates TreeMaps:</p> <pre><code>Map&lt;String, Integer&gt; map = new TreeMap&lt;String, Integer&gt;(); Words t = new Words(); MyComparator comp = w.(new MyComparator(map)); Map&lt;String, Integer&gt; tree = new TreeMap&lt;String, Integer&gt;(comp); int size = Integer.parseInt(buffer.readLine()); for(int i = size; i&gt;0; i--){ reader = buffer.readLine(); if(map.get(reader)!=null){ map.put(reader, map.get(reader)+1); } else map.put(reader, 1); } tree.putAll(map); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload