Posted By

zxeem on 02/16/10


Tagged

sort java map values Comparator


Versions (?)

Java Map Sorter Method Based on Map Values and Comparator


 / Published in: Java
 

  1.  
  2. /**
  3. * A helper method that sorts the map sent, based on sorting its values
  4. * using the comparator passed with it
  5. *
  6. * @param input The map to be sorted
  7. * @param comparator the comparator to be used to sort the map values
  8. *
  9. * @return A new Sorted HashMap that holds the values
  10. *
  11. * @author DKasem
  12. * @since Feb 15, 2010
  13. * @version 0.4.2
  14. */
  15. public static <T,E> Map<T, E> sortMap(final Map<T, E> input,Comparator<E> comparator){
  16. Map<T, E> tempMap = new HashMap<T, E>();
  17. for (T wsState : input.keySet()){
  18. tempMap.put(wsState,input.get(wsState));
  19. }
  20.  
  21. List<T> mapKeys = new ArrayList<T>(tempMap.keySet());
  22. List<E> mapValues = new ArrayList<E>(tempMap.values());
  23.  
  24. // Resultant map
  25. HashMap<T, E> sortedMap = new LinkedHashMap<T, E>();
  26.  
  27. List<E> sortedList = new ArrayList<E>(mapValues);
  28. Collections.sort(sortedList,comparator);
  29. for (int i=0; i<sortedList.size(); i++){
  30. sortedMap.put(mapKeys.get(mapValues.indexOf(sortedList.get(i))),(E)sortedList.get(i));
  31. }
  32. return sortedMap;
  33. }

Report this snippet  

You need to login to post a comment.