/ Published in: Java
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * A helper method that sorts the map sent, based on sorting its values * using the comparator passed with it * * @param input The map to be sorted * @param comparator the comparator to be used to sort the map values * * @return A new Sorted HashMap that holds the values * * @author DKasem * @since Feb 15, 2010 * @version 0.4.2 */ public static <T,E> Map<T, E> sortMap(final Map<T, E> input,Comparator<E> comparator){ Map<T, E> tempMap = new HashMap<T, E>(); for (T wsState : input.keySet()){ tempMap.put(wsState,input.get(wsState)); } List<T> mapKeys = new ArrayList<T>(tempMap.keySet()); List<E> mapValues = new ArrayList<E>(tempMap.values()); // Resultant map HashMap<T, E> sortedMap = new LinkedHashMap<T, E>(); List<E> sortedList = new ArrayList<E>(mapValues); for (int i=0; i<sortedList.size(); i++){ sortedMap.put(mapKeys.get(mapValues.indexOf(sortedList.get(i))),(E)sortedList.get(i)); } return sortedMap; }