How to sort the values of a HashMap in Java

If you want to sort a HashMap and keep the duplicate entries then see the solution in this article. Otherwise, read this article!

TASK
I want to sort my HashMap entries depending on the value of each one of them. I do not care about duplicate entries - duplicate entries are ignored by using this method. My HashMap is named as unSorted and it has values. In other words, it is defined as:

HashMap<String, Double> unSorted = new HashMap<String, Double>();

Now we put some sample entries in the HashMap, just to have something to order.

unSorted.put("Bristol", 23.45);
unSorted.put("London", 345.122);
unSorted.put("Manchester", 12.3);
unSorted.put("Edinburgh", 11.4);

Then we write a method that is able to take a HashMap as an input and after doing some crazy staff, it outputs the same HashMap but with its values sorted (ascending).

SOLUTION
This is the source code of the method:

private HashMap<String, Double> sortHashMap(HashMap<String, Double> input){
Map<String, Double> tempMap = new HashMap<String, Double>();
for (String wsState : input.keySet()){
tempMap.put(wsState,input.get(wsState));
}

List<String> mapKeys = new ArrayList<String>(tempMap.keySet());
List<Double> mapValues = new ArrayList<Double>(tempMap.values());
HashMap<String, Double> sortedMap = new LinkedHashMap<String, Double>();
TreeSet<Double> sortedSet = new TreeSet<Double>(mapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
for (int i=0; i<size; i++){
sortedMap.put(mapKeys.get(mapValues.indexOf(sortedArray[i])),
(Double)sortedArray[i]);
}
return sortedMap;
}

Now, to retrieve a HashMap with sorted values, you just have to use(!) the method above.

HashMap<String, Double> sorted = new HashMap<String, Double>();
sorted = sortHashMap(unSorted);

If we print the sorted HashMap...

for (String cityName : sorted.keyset()){
System.out.println(cityName + " " + sorted.get(cityName));
}

we get:

Edinburgh 11.4
Manchester 12.3
Bristol 23.45
London 345.122

I think sorting a hashmap is

I think sorting a hashmap is the worst job to do since it's a hashmap or hashtable, we expected the hashing to speed up the search , applying sort functionality is equal to losing hash functionality.

Sorting a hashmap is stupid

bill's picture

I totally agree with you. Sorting a hashmap cancels hashing. However, this post is useful for two reasons:

  • It indicates how many people use HashMaps in the wrong way.
  • It offers a solution in a case where small sized HashMaps are being used. It is very convenient to use HashMap type as its definition IS a benefit to the programmer; sorting a small HashMap does not cost more (even in the long term).

hashmap is stupid

It indicates how many people use HashMaps in the wrong way.

HashMap is not stupid

bill's picture

Using HashMaps is not stupid, sorting them is! -:) ... lots and lots of people (including me in the past).

HashMap Sorting

If a 'hashing' algorithm is used to recode a key to a value, then it makes no difference at all what the
stored order of the keys is - the incoming (key) is hashed to a result(value)...the HashMap had no
implied order when created (or it wouldn't be a HashMap) and sorting its keys(or values) does
nothing to the algorithm.
Sorting the keys(or values) only serves to allow humans to scan the object more easily - either in debugging
or offline inspection (as I just did for a small app that generated command/abbreviation synonyms).
If you can offer proof (benchmark example) that sorting a HashMap degrades performance in some way,
then I suggest that the writers have not written a true hashing mechanism...but something else :)

The article is very

The article is very informative as well as so creative. You have very great knowledge having this subject. Thanks.

Convert HashMap to TreeMap

To sort a HashMap the most simple way is this: Map sortedMap = new TreeMap(yourMap); The TreeMap is default sorted

Wow you posses a great amount

Wow you posses a great amount of knowledge, thanks for sharing.Forex Strategy Builder is a visual forex strategy backtester. It uses combination of technical indicators and logic rules to simulate a forex trade. James Dicks Mr Forex Author forex made easy provides education and training for stocks, options and foreign currency with PremiereTrade software.forex softwareAutomated forex trading software scans the market for favorable trades based on your input. Find out more about this valuable forex tool. Consumer reports of the best forex software. Check the latest ratings and comparisons of forex trading software on the market today.

Thanx

Thanx yaar. This method is very usefull. Specially for me...
Keep it Up..

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <p>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.