Posts Tagged With ‘TreeMap&8217

Sort a Map by its value

Below is a method which takes input as an unsorted map and returns a sorted one.
The task is accomplished by creating an anonymous java class.

For example: if original map is


The returned map would look like


public static > Map sortByValues(final Map map)
		Comparator valueComparator = new Comparator() {
			public int compare(K k1, K k2)
					int compare = map.get(k2).compareTo(map.get(k1));
					if (compare == 0)
						return 1;
					else return compare;
		Map sortedByValues = new TreeMap(valueComparator);
		return sortedByValues;

Let me know if you have a question.