Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can't sort a <code>HashMap</code>, but you can sort its entries obtained with <code>entrySet()</code>.</p> <pre><code>public class MapSort { private static class Employee { public String name; public Employee(String name) { this.name = name; } @Override public String toString() { return name; } } public static void main(String[] args) { Map&lt;Integer, Employee&gt; map = new HashMap&lt;Integer, Employee&gt;(); map.put(1, new MapSort.Employee("x")); map.put(2, new MapSort.Employee("a")); map.put(3, new MapSort.Employee("f")); List&lt;Map.Entry&lt;Integer, Employee&gt;&gt; entryList = new ArrayList&lt;Map.Entry&lt;Integer, Employee&gt;&gt;(map.entrySet()); Collections.sort( entryList, new Comparator&lt;Map.Entry&lt;Integer, Employee&gt;&gt;() { @Override public int compare(Map.Entry&lt;Integer, Employee&gt; integerEmployeeEntry, Map.Entry&lt;Integer, Employee&gt; integerEmployeeEntry2) { return integerEmployeeEntry.getValue().name .compareTo(integerEmployeeEntry2.getValue().name); } } ); System.out.println(entryList); } } </code></pre> <p>After sorting you can put back your entries in a map that supports ordering, for example <a href="http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html" rel="nofollow">LinkedHashMap</a>. </p> <p>It depends on your use case: if you need to keep the map always sorted it's simpler to employ a <code>TreeMap</code> that comes with an additional overhead. If you need just an one time sorting, you can use a <code>HashMap</code> with the above code.</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.
    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