Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Olof's answer is good, but it needs <em>one</em> more thing before it's perfect. In the comments below his answer, dacwe (correctly) points out that his implementation violates the Compare/Equals contract for Sets. If you try to call contains or remove on an entry that's clearly in the set, the set won't recognize it because of the code that allows entries with equal values to be placed in the set. So, in order to fix this, we need to test for equality between the keys:</p> <pre><code>static &lt;K,V extends Comparable&lt;? super V&gt;&gt; SortedSet&lt;Map.Entry&lt;K,V&gt;&gt; entriesSortedByValues(Map&lt;K,V&gt; map) { SortedSet&lt;Map.Entry&lt;K,V&gt;&gt; sortedEntries = new TreeSet&lt;Map.Entry&lt;K,V&gt;&gt;( new Comparator&lt;Map.Entry&lt;K,V&gt;&gt;() { @Override public int compare(Map.Entry&lt;K,V&gt; e1, Map.Entry&lt;K,V&gt; e2) { int res = e1.getValue().compareTo(e2.getValue()); if (e1.getKey().equals(e2.getKey())) { return res; // Code will now handle equality properly } else { return res != 0 ? res : 1; // While still adding all entries } } } ); sortedEntries.addAll(map.entrySet()); return sortedEntries; } </code></pre> <p>"Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface... the Set interface is defined in terms of the equals operation, but <strong>a sorted set performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal</strong>." (<a href="http://docs.oracle.com/javase/6/docs/api/java/util/SortedSet.html">http://docs.oracle.com/javase/6/docs/api/java/util/SortedSet.html</a>)</p> <p>Since we originally overlooked equality in order to force the set to add equal valued entries, now we have to test for equality in the keys in order for the set to actually return the entry you're looking for. This is kinda messy and definitely not how sets were intended to be used - but it works.</p>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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