How does Java sort maps to detail the use of of map collections

  • 2020-04-01 02:31:26
  • OfStack

Today, when we do statistics, we need to sort the X-axis regions by areaCode, and since the map used in building XMLData is used for data statistics, we need to sort the map during the statistics.

A brief introduction to Map

Before we talk about Map sorting, let's look at maps a little bit. The map is a collection of key/value pair interface, its implementation class mainly includes: HashMap, TreeMap, Hashtable and LinkedHashMap. The differences among the four are as follows (a brief introduction) :

A HashMap : the most commonly used Map, which stores data according to the HashCode Value of key, can get its Value directly according to key, and it has a fast access speed. A HashMap allows at most one record to have a Null key value (multiple records overwrite); Allows multiple records to have a Null Value. Asynchronous.

TreeMap : the ability to sort its saved records by key, in ascending order by default, or to specify the sort comparator, so that when traversing the TreeMap with the Iterator, the resulting records are sorted. TreeMap does not allow the value of key to be null. Asynchronous.

Hashtable : similar to HashMap, except that key and value are not allowed to be null; It supports synchronization of threads, meaning that only one thread can write Hashtable at any one time, which also causes Hashtale to be slow to write.

LinkedHashMap: holds the insertion order of the records, and when iterating over the LinkedHashMap with Iterator, the first obtained records must be inserted first. Key and value are allowed to be null and asynchronous.

 

Map sort

TreeMap

TreeMap is ascending by default, and if we need to change the sorting, we need to use the Comparator: Comparator.

The Comparator interface of the Comparator can sort collection objects or arrays, and the public compare(T o1,To2) method of the interface can be sorted. This method mainly returns negative integer, 0 or positive integer if it is less than, equal to or greater than o2 according to the first parameter o1. 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) {
                        //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 sorts by the key value of the TreeMap, but sometimes we need to sort by the value of the TreeMap. To sort the value we need the Collections sort(List< T> The list, Comparator< ? Super T> C) method that sorts the specified list in the order produced by the specified comparator. However, there is a prerequisite that all elements must be able to be compared according to 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, map.entryset () is converted to a list
        List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
        //Then sort through the comparator
        Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
            //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()); 
          } 
    }
}


The results

A: aaaaa
B: BBBBB
C: CCCCC
D: DDDDD

A HashMap

We are all HashMap values are in no order, they are implemented according to the key's HashCode. How do we implement sorting for this unordered HashMap? By referring to the value sort of TreeMap, we can also implement the sort of HashMap.


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>>() {
            //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()); 
          } 
     }
}

The results

A: aaaaa
B: BBBBB
C: CCCCC
D: DDDDD


Related articles: