Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A <a href="http://java.sun.com/javase/6/docs/api/java/util/HashMap.html" rel="noreferrer"><code>HashMap</code></a> (and its legacy predecesor <a href="http://java.sun.com/javase/6/docs/api/java/util/Hashtable.html" rel="noreferrer"><code>Hashtable</code></a>) is by nature unordered. Even if you sort it, it will remain unordered. If you want to maintain insertion order, then use <a href="http://java.sun.com/javase/6/docs/api/java/util/LinkedHashMap.html" rel="noreferrer"><code>LinkedHashMap</code></a> instead. If you want an automatic sort on <strong>keys</strong>, regardless of insertion order, then use <a href="http://java.sun.com/javase/6/docs/api/java/util/SortedMap.html" rel="noreferrer"><code>SortedMap</code></a> instead.</p> <p>If you want to sort a <code>Map</code> on <strong>values</strong>, then you basically need to put the key/value pairs in another kind of a sortable data structure, e.g. <code>List&lt;Entry&lt;K, V&gt;&gt;</code>, then sort it using <code>Collections#sort()</code> with help of a <code>Compatator&lt;Entry&lt;K, V&gt;&gt;</code> and finally repopulate a <code>LinkedHashMap</code> with it (not a <code>HashMap</code> or you will lose the ordering again).</p> <p>Here's a basic example (leaving obvious runtime exception handling aside):</p> <pre><code>// Prepare. Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); map.put("foo", "bar"); map.put("bar", "waa"); map.put("waa", "foo"); System.out.println(map); // My JVM shows {waa=foo, foo=bar, bar=waa} // Get entries and sort them. List&lt;Entry&lt;String, String&gt;&gt; entries = new ArrayList&lt;Entry&lt;String, String&gt;&gt;(map.entrySet()); Collections.sort(entries, new Comparator&lt;Entry&lt;String, String&gt;&gt;() { public int compare(Entry&lt;String, String&gt; e1, Entry&lt;String, String&gt; e2) { return e1.getValue().compareTo(e2.getValue()); } }); // Put entries back in an ordered map. Map&lt;String, String&gt; orderedMap = new LinkedHashMap&lt;String, String&gt;(); for (Entry&lt;String, String&gt; entry : entries) { orderedMap.put(entry.getKey(), entry.getValue()); } System.out.println(orderedMap); // {foo=bar, waa=foo, bar=waa} </code></pre> <p>To sort it <strong>descencing</strong>, use the following <code>Comparator</code>. Basically just swap the entries to compare:</p> <pre><code>Collections.sort(entries, new Comparator&lt;Entry&lt;String, String&gt;&gt;() { public int compare(Entry&lt;String, String&gt; e1, Entry&lt;String, String&gt; e2) { return e2.getValue().compareTo(e1.getValue()); // Sorts descending. } }); </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