Several Java examples that sort the keys or values of a map. Attention:
If you are using Java 8, refer to this article –java 8– How to sort the map 1. Sort by Key
1.1 with Java.util.TreeMap, it will automatically sort the map according to the keys. Sortbykeyexample1.java
Package com.mkyong.test;
Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.TreeMap; public class SortByKeyExample1 {public static void main (string[] args) {map<string, string> Unsortma
p = new hashmap<string, string> ();
Unsortmap.put ("z", "Z");
Unsortmap.put ("B", "B");
Unsortmap.put ("A", "a");
Unsortmap.put ("C", "C");
Unsortmap.put ("D", "D");
Unsortmap.put ("E", "E");
Unsortmap.put ("Y", "Y");
Unsortmap.put ("n", "n");
Unsortmap.put ("J", "J");
Unsortmap.put ("M", "M");
Unsortmap.put ("F", "F");
System.out.println ("Unsort Map ...");
Printmap (UNSORTMAP); System.out.println ("\nsorted Map ...")
by Key ");
map<string, string> treeMap = new treemap<string, string> (UNSORTMAP);
Printmap (TREEMAP); }//pretty print a map public static <k, v> void Printmap (map<k, v> map) {for (map.entRy<k, v> Entry:map.entrySet ()) {System.out.println ("Key:" + entry.getkey () + "Value:" + entr
Y.getvalue ()); }
}
}
Output
Unsort Map ...
Key:a value:a
key:b value:b
key:c value:c
key:d
value:d
key:e value:e key:f valu E:f
key:y value:y
key:z value:z
key:j
value:j key:m value:m key:n value:n Sorted Map ... by Key
key:a value:a
key:b value:b
key:c value:c
key:d value:d key:e value:e<
C17/>key:f value:f
key:j value:j
key:m value:m
key:n
value:n
key:y value:y Ke Y:z value:z
1.2 Another JAVA.UTIL.TREEMAP example, provides a custom Comparator pair that can be sorted in descending order. Sortbykeyexample2.java
Package com.mkyong.test;
Import Java.util.Comparator;
Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.TreeMap; public class SortByKeyExample2 {public static void main (string[] args) {map<integer, string> Unsortm
AP = new Hashmap<integer, string> ();
Unsortmap.put ("Z");
Unsortmap.put (5, "B");
Unsortmap.put (6, "a");
Unsortmap.put ("C");
Unsortmap.put (1, "D");
Unsortmap.put (7, "E");
Unsortmap.put (8, "Y");
Unsortmap.put ("n");
Unsortmap.put (M, "J");
Unsortmap.put (2, "M");
Unsortmap.put (9, "F");
System.out.println ("Unsort Map ...");
Printmap (UNSORTMAP); System.out.println ("\nsorted Map ...")
by Key "); Map<integer, string> treeMap = new Treemap<integer, string> (New comparator<integer> (