Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. import java.util.*;
  2. import java.lang.*;
  3. class HashMapSorter
  4. {
  5. public static void main(String arg[])
  6. {
  7. HashMap<String,Integer> mapproduct = new HashMap();
  8. mapproduct.put("1",2);mapproduct.put("2",1);
  9. System.out.println("Before Sorting:"+mapproduct);
  10. Map<String, Integer> sorted = sortByKeys(mapproduct);
  11. System.out.println("After Sorting :"+sorted);
  12. }
  13. public static <K extends Comparable,V extends Comparable> Map<K,V> sortByKeys(Map<K,V> map){
  14. List<K> keys = new LinkedList<K>(map.keySet());
  15. Collections.sort(keys);
  16.  
  17. //LinkedHashMap will keep the keys in the order they are inserted
  18. //which is currently sorted on natural ordering
  19. Map<K,V> sortedMap = new LinkedHashMap<K,V>();
  20. for(K key: keys){
  21. sortedMap.put(key, map.get(key));
  22. }
  23.  
  24. return sortedMap;
  25. }
  26.  
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement