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

{("sample1",58),("string3",34),("delta",85)}

The returned map would look like

{("delta",85),("sample1",58),("string3",34)}

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);
		sortedByValues.putAll(map);
		return sortedByValues;
	}

Let me know if you have a question.


One Response
  • adam Reply

    Thanks for posting this.

Leave a Reply