Sort an HashMap based on the keys in Java

Description

The following code shows how to sort an HashMap based on the keys.

Example


/*from w w  w  .  ja  v  a  2 s . c om*/
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Main {

  public static void main(String[] a) {
    Map<String, String> yourMap = new HashMap<String, String>();
    yourMap.put("1", "one");
    yourMap.put("2", "two");
    yourMap.put("3", "three");

    Map<String, String> sortedMap = new TreeMap<String, String>(yourMap);

    System.out.println(sortedMap);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Collection »




Java ArrayList
Java Collection
Java Comparable
Java Comparator
Java HashMap
Java HashSet
Java Iterator
Java LinkedHashMap
Java LinkedHashSet
Java LinkedList
Java List
Java ListIterator
Java Map
Queue
Java Set
Stack
Java TreeMap
TreeSet