gogoWebsite

Detailed explanation of how Java sorts Map (using map collections)

Updated to 23 days ago

1. Brief introduction to Map

Before explaining Map sorting, let’s take a closer look at maps. map is a collection interface for key-value pairs. Its implementation classes mainly include: HashMap, TreeMap, Hashtable, and LinkedHashMap. The difference between these four is as follows (simple introduction):

HashMap:The most commonly used Map is used by us. It stores data based on the HashCode value of the key. It can directly obtain its value according to the key, and it has a very fast access speed. HashMap allows only one record to have a key value of Null at most (multiple records will be overwritten); the value of multiple records to have a value of Null. Asynchronous.

TreeMap: The records saved can be sorted according to the key, and the default is to sort in ascending order. You can also specify the sorted comparator. When it is traversed with the Iterator, the records obtained are sorted. TreeMap does not allow the value of key to be null. Asynchronous.

Hashtable: Similar to HashMap, the difference is that the values ​​of key and value are not allowed to be null; it supports thread synchronization, that is, only one thread can write a Hashtable at any time, which also causes Hashtale to be slower when writing.

LinkedHashMap: Save the insertion order of records. When traversing LinkedHashMap with Iterator, the first record must be inserted first. It will be slower than HashMap during traversal. Both key and value are allowed to be empty and asynchronous.

2. Map sorting

TreeMap

TreeMap is in ascending order by default. If we need to change the sorting method, we need to use a comparator: Comparator.

Comparator can sort the comparator interface for the collection object or array, and implement the public comparison(T o1,To2) method of this interface to realize the sorting. This method mainly returns negative integers, 0 or positive integers based on the first parameter o1, less than, equal to or greater than o2, respectively. The code is as follows:

public class TreeMapTest {
     public static void main(String[] args) {
         Map<String, String> map = new TreeMap<String, String>(
                 new Comparator<String>() {
                     public int compare(String obj1, String obj2) {
                         // Sort in descending order
                         return (obj1);
                     }
                 });
         ("c", "cccccc");
         ("a", "aaaaa");
         ("b", "bbbbbb");
         ("d", "ddddd");

         Set<String> keySet = ();
         Iterator<String> iter = ();
         while (()) {
             String key = ();
             (key + ":" + (key));
         }
     }
 }

The operation results are as follows:
d:ddddd
c:ccccc
b:bbbbb
a:aaaaa

The above example is to sort according to the key value of TreeMap, but sometimes we need to sort according to the value of TreeMap. To sort value, we need to use the sort(List<T> list, Comparator<? super T> c) method of Collections, which sorts the specified list according to the order generated by the specified comparator. But there is a prerequisite, that is, all elements must be able to be compared based on the provided comparator. as follows:

public class TreeMapTest {
     public static void main(String[] args) {
         Map<String, String> map = new TreeMap<String, String>();
         ("d", "ddddd");
         ("b", "bbbbbb");
         ("a", "aaaaa");
         ("c", "cccccc");

         // Here you convert () to list
         List<<String,String>> list = new ArrayList<<String,String>>(());
         //Then the order is achieved through the comparator
         (list,new Comparator<<String,String>>() {
             //Sorting ascending order
             public int compare(Entry<String, String> o1,
                     Entry<String, String> o2) {
                 return ().compareTo(());
             }
         });
         for(<String,String> mapping:list){ (()+":"+());
           }
     }
 }

The operation results are as follows:
d:ddddd
c:ccccc
b:bbbbb
a:aaaaa

HashMap

We all have HashMap values ​​that have no order, and they are implemented according to the HashCode of the key. How do we implement sorting for this unordered HashMap? Referring to the value sort of TreeMap, we can also implement HashMap sorting.

public class HashMapTest {
     public static void main(String[] args) {
         Map<String, String> map = new HashMap<String, String>();
         ("c", "cccccc");
         ("a", "aaaaa");
         ("b", "bbbbbb");
         ("d", "ddddd");

         List<<String,String>> list = new ArrayList<<String,String>>(());
         (list,new Comparator<<String,String>>() {
             //Sorting ascending order
             public int compare(Entry<String, String> o1,
                     Entry<String, String> o2) {
                 return ().compareTo(());
             }

         });

         for(<String,String> mapping:list){
                (()+":"+());
           }
      }
 }

The operation results are as follows:
d:ddddd
c:ccccc
b:bbbbb
a:aaaaa