Here we can get two different methods to sort a map in Java.
Source Code
1) Sort by Key
package com.beginner.examples;
import java.util.*;
public class SortMapExample1 {
public static void main(String[] args) {
Map map = new HashMap();
map.put("1", "one");
map.put("3", "three");
map.put("2", "two");
Map treeMap = new TreeMap(map);
for (Map.Entry e : treeMap.entrySet()) {
System.out.println("Key : " + e.getKey() + " , Value : " + e.getValue());
}
}
}
Output:
Key : 1 , Value : one
Key : 2 , Value : two
Key : 3 , Value : three
2) Sort by Value
package com.beginner.examples;
import java.util.*;
public class SortMapExample2 {
public static void main(String[] args) {
Map map = new HashMap();
map.put("one" , "1");
map.put("three" , "3");
map.put("two" , "2");
List<Map.Entry> list = new ArrayList<Map.Entry>(map.entrySet());
Collections.sort(list,new Comparator<Map.Entry>() {
public int compare(Map.Entry c1,
Map.Entry c2) {
return c1.getValue().compareTo(c2.getValue());
}
});
for(Map.Entry mapping:list){
System.out.println("Key : " + mapping.getKey() + " , Value : " + mapping.getValue());
}
}
}
Output:
Key : one , Value : 1
Key : two , Value : 2
Key : three , Value : 3
References
Imported packages in Java documentation: