Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a snippet that uses a generic method that takes a <code>Map&lt;K,V&gt;</code> and a <code>Comparator&lt;? super V&gt;</code>, and returns a <code>SortedSet</code> of its <code>entrySet()</code> sorted on the values using the comparator.</p> <pre><code>public class MapSort { static &lt;K,V&gt; SortedSet&lt;Map.Entry&lt;K,V&gt;&gt; entriesSortedByValues(Map&lt;K,V&gt; map, final Comparator&lt;? super V&gt; comp) { 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(Entry&lt;K, V&gt; e1, Entry&lt;K, V&gt; e2) { return comp.compare(e1.getValue(), e2.getValue()); } } ); sortedEntries.addAll(map.entrySet()); return sortedEntries; } static class Custom { final double d; Custom(double d) { this.d = d; } @Override public String toString() { return String.valueOf(d); } } public static void main(String[] args) { Map&lt;String,Custom&gt; map = new HashMap&lt;String,Custom&gt;(); map.put("A", new Custom(1)); map.put("B", new Custom(4)); map.put("C", new Custom(2)); map.put("D", new Custom(3)); System.out.println( entriesSortedByValues(map, new Comparator&lt;Custom&gt;() { @Override public int compare(Custom c1, Custom c2) { return Double.compare(c1.d, c2.d); } }) ); // prints "[A=1.0, C=2.0, D=3.0, B=4.0]" } } </code></pre> <hr> <h3>On Google Ordering</h3> <blockquote> <p><a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Ordering.html#from%28java.util.Comparator%29" rel="nofollow noreferrer"><code>public static &lt;T&gt; Ordering&lt;T&gt; from(Comparator&lt;T&gt; comparator)</code></a></p> <p>Returns an ordering for a pre-existing comparator.</p> </blockquote> <p>The above solution uses a <code>Comparator</code>, so you can easily use the above method to use <code>Ordering</code> instead.</p>
 

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