Sort an HashMap based on the keys : HashMap « Collections « Java Tutorial






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);
  }
}
//{1=one, 2=two, 3=three}








9.26.HashMap
9.26.1.HashMap Class: a basic key-value map where the elements are unordered
9.26.2.Iterate through the values of HashMap
9.26.3.Get Synchronized Map from HashMap
9.26.4.Check if a particular key exists in HashMap
9.26.5.Check if a particular value exists in HashMap
9.26.6.For keys of a map
9.26.7.For values of a map
9.26.8.For both the keys and values of a map
9.26.9.Storing Primitive Types in a Collection
9.26.10.Get Set view of Keys from HashMap
9.26.11.Get Size of HashMap
9.26.12.Adding Key-Value Pairs: public Object put(Object key, Object value)
9.26.13.If key is not in add the key value pair
9.26.14.Unlike a Hashtable, both the key and the value for a HashMap can be null
9.26.15.To copy all the key-value pairs from one Map into another: public void putAll(Map map)
9.26.16.Displaying Contents: public String toString()
9.26.17.Remove value from HashMap
9.26.18.Removing Key-Value Pairs: public Object remove(Object key)
9.26.19.Removal of all elements from a map: public void clear()
9.26.20.Sizing Hash Maps: find out the number of key-value pairs within the HashMap
9.26.21.Fetching Keys and Values: find a value based upon a specific key with: public Object get(Object key)
9.26.22.Getting the set of all keys with the keySet() method: public Set keySet()
9.26.23.To get the set of all the values in the hash map: public Collection values()
9.26.24.To get a set of Map.Entry elements back from a HashMap: public Set entrySet()
9.26.25.Finding Elements
9.26.26.Cloning Hash Map: public Object clone()
9.26.27.Creating a Copy of a Collection: the objects are not cloned.
9.26.28.Checking Hash Maps for Equality: public boolean equals(Object o)
9.26.29.Sort an HashMap based on the keys
9.26.30.Serializing Hash Maps
9.26.31.Use Iterator to loop through the map key set
9.26.32.Create Java Hashtable from HashMap
9.26.33.How do I...Store simple pairs of data for quick lookup?