title: Best way to order an HashMap by key in Java?
body: <p>This is the first time that I have to order an <code>HashMap</code> in Java. I need to do that by key but in my case the key is an object so I need to order by a specific field. Trying to figure it by my own I've considered to proceed with this simple scratch of code:</p>
  
  <pre><code>private HashMap&lt;SimpleDBField, String&gt; sortTable(HashMap&lt;SimpleDBField, String&gt; row){
  
      LinkedHashMap&lt;SimpleDBField, String&gt; orderedRow = new LinkedHashMap&lt;SimpleDBField, String&gt;();
  
      for(int i = 1; i &lt;= row.size(); i ++){
          Iterator iterator = row.entrySet().iterator();
  
          while(iterator.hasNext()){
              Map.Entry&lt;SimpleDBField, String&gt; entry = (Map.Entry&lt;SimpleDBField, String&gt;) iterator.next();
  
              if(entry.getKey().getListPosition()==i){
                  orderedRow.put(entry.getKey(), entry.getValue());
                  break;
              }
          }
      }
  
      return orderedRow;
  }
  </code></pre>
  
  <p>Assuming that it works and I don't care about performance, before really use it, I wish to know if the next scratch of code could be better and most important: Why?</p>
  
  <p>Example below source here: <a href="http://javarevisited.blogspot.it/2012/12/how-to-sort-hashmap-java-by-key-and-value.html" rel="nofollow">How to sort HashMap by key and value in Java</a></p>
  
  <pre><code>public static &lt;K extends Comparable,V extends Comparable&gt; Map&lt;K,V&gt; sortByKeys(Map&lt;K,V&gt; map){
  
      List&lt;K&gt; keys = new LinkedList&lt;K&gt;(map.keySet());
  
      Collections.sort(keys);
  
      Map&lt;K,V&gt; sortedMap = new LinkedHashMap&lt;K,V&gt;();
  
      for(K key: keys){
          sortedMap.put(key, map.get(key));
  
      }
  
      return sortedMap;
  }
  </code></pre>
  
  <p>If both are wrong, how should I do that?</p>