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.