Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As polygenelubricants nicely explained, a <code>SortedMap</code> is sorted by the <strong>key</strong>, not by the <strong>value</strong>. </p> <p>However, it's with help of <a href="http://java.sun.com/javase/6/docs/api/java/util/LinkedHashMap.html" rel="nofollow noreferrer"><code>LinkedHashMap</code></a> possible to reorder a <code>Map</code> the way you want. A <code>LinkedHashMap</code> maintains insertion order like a <code>List</code> does. </p> <p>First step is to get hold of the key/value pairs in a sortable data structure, e.g. <code>List&lt;Entry&lt;K, V&gt;&gt;</code> which you in turn sort using <a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29" rel="nofollow noreferrer"><code>Collections#sort()</code></a> 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>Needless to say that this is after all not the <em>right</em> datastructure for your purpose ;)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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