Sunday, June 26, 2011

Java Map Sorter Method Based on Map Values and Comparator!

/**
     * 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 Varra
     * @version 0.4.2
     */
    public static <T, E> Map<T, E> sortMap(final Map<T, E> input, Comparator<E> comparator)
    {
        final Map<T, E> tempMap = new HashMap<T, E>();
        for (T wsState : input.keySet())
        {
            tempMap.put(wsState, input.get(wsState));
        }
        final List<T> mapKeys = new ArrayList<T>(tempMap.keySet());
        final List<E> mapValues = new ArrayList<E>(tempMap.values());
        // Resultant map
        final HashMap<T, E> sortedMap = new LinkedHashMap<T, E>();
        final 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;
    }

No comments:

Post a Comment