Sorting HashMap based on its values

This task could be done in different ways. Here a discussion about some ways.
In this post I will show one that I followed. Roughly speaking, the idea is convert the map into a list with the purpose of use the classic Collection.sort() method.
The first think is that you need is to define a new class, that represents one map entry; and implements the Comparable interface. In this class you have to implement the compareTo method and override the toString (if you want).

import java.util.Map;

public class CustomEntry implements Comparable
	private Map.Entry	entry;

	public CustomEntry(Map.Entry entry)
		this.entry = entry;

	public Map.Entry getEntry()
		return this.entry;

	public int compareTo(CustomEntry anotherEntry)
		Integer thisIntegerVal = (Integer) (this.getEntry().getValue());
		int thisVal = thisIntegerVal.intValue();
		Integer anotherIntegerVal = (Integer) (anotherEntry.getEntry().getValue());
		int anotherVal = anotherIntegerVal.intValue();
		return (thisVal < anotherVal ? 1 : (thisVal == anotherVal ? 0 : -1));

	public int compareTo(Object o)
		return compareTo((CustomEntry) o);

	public String toString()
		StringBuilder str = new StringBuilder();
		return str.toString();

Next step is to define the function that will convert any map into a list. Basically, this function will recover the entries in the map, and transform them into custom entries using the previous class CustomEntry.

import java.util.*;
import java.util.Map.Entry;

public class MapFunctions
	public MapFunctions()

	public static <T, E> List<CustomEntry> convertMapToList(Map<T, E> map)
		List<CustomEntry> list = new ArrayList<CustomEntry>();
		Set<Entry<T, E>> entrySet = map.entrySet();
		Iterator<Entry<T, E>> iterator = entrySet.iterator();
		while (iterator.hasNext())
			Map.Entry<T, E> entry = (Map.Entry<T, E>);
			CustomEntry customEntry = new CustomEntry(entry);
		return list;

Now, you are allowed to execute the following instructions:

THashMap<String, Integer> map = ... /* some initialization */
List<CustomEntry> sortedList = MapFunctions.convertMapToList(map);

and you will print the list of entries (from your original map) sorted based on its (original) values.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s