Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.lang.*;
- class HashMapSorter
- {
- public static void main(String arg[])
- {
- HashMap<String,Integer> mapproduct = new HashMap();
- mapproduct.put("1",2);mapproduct.put("2",1);
- System.out.println("Before Sorting:"+mapproduct);
- Map<String, Integer> sorted = sortByKeys(mapproduct);
- System.out.println("After Sorting :"+sorted);
- }
- public static <K extends Comparable,V extends Comparable> Map<K,V> sortByKeys(Map<K,V> map){
- List<K> keys = new LinkedList<K>(map.keySet());
- Collections.sort(keys);
- //LinkedHashMap will keep the keys in the order they are inserted
- //which is currently sorted on natural ordering
- Map<K,V> sortedMap = new LinkedHashMap<K,V>();
- for(K key: keys){
- sortedMap.put(key, map.get(key));
- }
- return sortedMap;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement