Return to Snippet

Revision: 23874
at February 16, 2010 05:47 by zxeem


Initial Code
	/**
	 * 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);
	    Collections.sort(sortedList,comparator);
	    for (int i=0; i<sortedList.size(); i++){
	        sortedMap.put(mapKeys.get(mapValues.indexOf(sortedList.get(i))),(E)sortedList.get(i));
	    }
	    return sortedMap;
	}

Initial URL

                                

Initial Description

                                

Initial Title
Java Map Sorter Method Based on Map Values and Comparator

Initial Tags
sort, java

Initial Language
Java