Translation Links: http://www.codeceo.com/article/java-hashmap-value-sort.html
The English version: How to Sort HashMap Based on the Values in Java
Translation Author: Code Rural network – Xiao Feng
HashMap in Java is a data structure for storing "key" and "value" information pairs. Unlike array, ArrayList, and linkedlists, it does not maintain the order in which elements are inserted.
Therefore, sorting hashmap on the basis of key or value is a difficult interview problem if you don't know how to solve it. Let's look at how to solve the problem below.
1. HashMap stores each pair of keys and values as a Entry<k,v> object. For example, give a hashmap,
map<string,integer> AMap = new hashmap<string,integer> ();
Each time a key is inserted, a value corresponds to the hash map, generating a entry <K,V> object. By using this entry <K,V> object, we can sort HashMap by value.
2. Create a simple hashmap and insert some keys and values.
ap<string,integer> AMap = new hashmap<string,integer> ();
Adding keys and Values
amap.put ("Five", 5);
Amap.put ("Seven", 7);
Amap.put ("Eight", 8);
Amap.put ("One", 1);
Amap.put ("Two", 2);
Amap.put ("Three", 3);
3. Restore the entry collection from the HashMap as shown below.
set<entry<string,integer>> mapentries = Amap.entryset ();
4. Create LinkedList from the above mapentries. We'll sort this list to solve the order problem. The reason we use a linked list to do this is because inserting elements in a linked list is faster than an array listing.
List<entry<string,integer>> alist = new linkedlist<entry<string,integer>> (mapEntries);
5. Use the Collections.sort () method to sort the list by passing the linked list and customizing the comparer.
Collections.sort (Alist, New comparator<entry<string,integer>> () {
@Override
pu Blic int Compare (entry<string, integer> ele1,
entry<string, integer> ele2) {
Return Ele1.getvalue (). CompareTo (Ele2.getvalue ());
}
});
6. Use a custom comparer to sort the list based on the Entry value (Entry.getvalue ()).
7. Ele1.getvalue (). CompareTo (Ele2.getvalue ())--compares these two values, returns 0--if the two values are identical; returns 1--if the first value is greater than the second; Returns -1--if the first value is less than the second value.
8. Collections.sort () is a built-in method that only sorts the list of values. It is overloaded in the collections class. Both of these methods are
public static <t extends Comparable<? Super t>> void Sort (list<t> list) public
static <T> void sort (list<t> list, comparator<? s Uper t> c)
9. Now that you have sorted the list, we need to store key and value information to the new mappings. Because HashMap do not keep order, we use Linkedhashmap.
Storing the list into linked HashMap to preserve the order of insertion.
map<string,integer> aMap2 = new linkedhashmap<string, integer> ();
for (entry<string,integer> entry:alist) {
amap2.put (Entry.getkey (), Entry.getvalue ());
}
10. The complete code is as follows.
Package com.speakingcs.maps;
Import java.util.Collections;
Import Java.util.Comparator;
Import Java.util.HashMap;
Import Java.util.LinkedHashMap;
Import java.util.LinkedList;
Import java.util.List;
Import Java.util.Map;
Import Java.util.Map.Entry;
Import Java.util.Set; public class Sortmapbyvalues { public static void main (string[] args) { MAP< ;
string,integer> AMap = new hashmap<string,integer> ();
//adding keys and values amap.put ("Five", 5);
amap.put ("Seven", 7);
Amap.put ("eight", 8);
Amap.put ("one", 1);
Amap.put ("two", 2);
amap.put ("Three", 3);
sortmapbyvalues (AMAP); } private static void Sortmapbyvalues (Map<string, integer> aMap) { &NBSP ; Set<entry<string,integer>> mapentries = Amap.entryset ();
SYSTEM.OUT.PRINTLN ("Values and Keys before sorting"); for (entry<string,integer> entry:mapentries) { &NBSP ;
System.out.println (Entry.getvalue () + "-" + Entry.getkey ()); } //used linked list to sort, because insertion of elements in L
Inked list is faster than a array list. list<entry<string,integer>> alist = new Linkedlist<entry<string,integer
>> (mapentries); //sorting the List Collections.sort (alist, New comparator<entr Y<string,integer>> () { @Override &N Bsp public int Compare (entry<string, integer> ele1,   Entry<string, integer> ele2) { return Ele1.getvalue (). Compa
ReTo (Ele2.getvalue ());
} }
//storing the list into linked HashMap to preserve the order of insertion.
map<string,integer> aMap2 = new linkedhashmap<string, integer> (); for (entry<string,integer> entry:alist) { AMAP
2.put (Entry.getkey (), Entry.getvalue ()); } //Printing values after soring of map &NB Sp
System.out.println ("Value" + "-" + "Key"); for (entry<string,integer> Entry:aMap2.entrySet ()) {
System.out.println (Entry.getvalue () + "-" + Entry.getkey ()); } &NBsp }}