If elements are stored in stored in HashMap or any other collection class that implements Map we can use TreeMap’s constructor to sort map on basis of key.
Let’s see Example >
HashMap -
Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
hashMap.put(4, 1);
hashMap.put(2, 1);
hashMap.put(3, 1);
|
TreeMap’s constructor -
Map<Integer, Integer> treeMap = new TreeMap<Integer, Integer>(hashMap);
|
Full program >
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class SortMapByKey {
public static void main(String...a){
Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
hashMap.put(4, 1);
hashMap.put(2, 1);
hashMap.put(3, 1);
//TreeMap's constructor
Map<Integer, Integer> treeMap = new TreeMap<Integer, Integer>(hashMap);
System.out.println("treeMap : "+treeMap);
}
}
/*OUTPUT
treeMap : {2=1, 3=1, 4=1}
*/
|
Important Note :
- If any class that implements Map contains null key - If any class that implements Map contains null key and is converted into TreeMap than NullPointerException (RunTimeException) will be thrown.
RELATED LINKS>