gogoWebsite

Ordered and unordered implementation classes of Map, sorting with Map

Updated to 23 days ago

Ordered and unordered implementation classes of Map, sorting with Map

, Hashtable is not ordered;
and LinkedHashMap are ordered (TreeMap defaults to ascending order, while LinkedHashMap records the insertion order).

When doing statistics today, we need to sort the X-axis regions according to the area code (areaCode). Since the map used by XMLData is used to perform data statistics, we need to sort the maps during the statistics process.

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 we use, it stores data based on the HashCode value of the key, and 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: It can sort the records it saves according to the key. By default, it is sorted in ascending order. You can also specify the sorted comparator. When it is traversed with 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 Hashtable at any time, which also causes Hashtale to be slower when writing.

  • LinkedHashMap: Saves 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. 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 obj2.compareTo(obj1);
                    }
                });
        map.put("c", "ccccc");
        map.put("a", "aaaaa");
        map.put("b", "bbbbb");
        map.put("d", "ddddd");
        
        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            System.out.println(key + ":" + map.get(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 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>();
        map.put("d", "ddddd");
        map.put("b", "bbbbb");
        map.put("a", "aaaaa");
        map.put("c", "ccccc");
        
        // Here you convert () to list
        List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
        //Then the order is achieved through the comparator
        Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
            //Sorting ascending order
            public int compare(Entry<String, String> o1,
                    Entry<String, String> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
            
        });
        
        for(Map.Entry<String,String> mapping:list){ 
               System.out.println(mapping.getKey()+":"+mapping.getValue()); 
          } 
    }
}
      a:aaaaa 
      b:bbbbb 
      c:ccccc 
      d:ddddd

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>();
            map.put("c", "ccccc");
            map.put("a", "aaaaa");
            map.put("b", "bbbbb");
            map.put("d", "ddddd");
            
            List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
            Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
                //Sorting ascending order
                public int compare(Entry<String, String> o1,
                        Entry<String, String> o2) {
                    return o1.getValue().compareTo(o2.getValue());
                }
                
            });
            
            for(Map.Entry<String,String> mapping:list){ 
                   System.out.println(mapping.getKey()+":"+mapping.getValue()); 
              } 
         }
    }

Running results

  a:aaaaa 
  b:bbbbb 
  c:ccccc 
  d:ddddd