Sorting Map

Sorting Map with Key and Values

Sorting Map with Key
As all we know, to sort a Map by its keys, uses TreeMap is good solution, and it sort Map keys automatically.

Solution
Map<String, String> treeMap = new TreeMap<String, String>(unsortMap);

Sorting Map with Value
TreeMap unable to sort the Map using values. We should use Comparator to sort the Map values,
1. Converts the Map into a List
2. Sorts the List by Comparator.
3. Add sorted list back to your Map if needed.

Solution
Set<Entry<Character, Integer>> inputSet = inputMap.entrySet();//Your input map

List<Entry<Character, Integer>> sortedList = new ArrayList<Entry<Character, Integer>>(inputSet);
Collections.sort( sortedList, new Comparator<Map.Entry<Character, Integer>>()
{
public int compare(Map.Entry<Character, Integer> firstObject, Map.Entry<Character, Integer> secondObject)
{
return (firstObject.getValue()).compareTo(secondObject.getValue() );
}
} );