Home > Java > javaTutorial > Implementation of Map sorting in java

Implementation of Map sorting in java

王林
Release: 2019-11-29 13:34:07
forward
2720 people have browsed it

Implementation of Map sorting in java

map is a collection interface of key-value pairs. Its implementation classes mainly include: HashMap<span style="font-family:Microsoft Yahei, Hiragino Sans GB, Helvetica, Helvetica Neue, 微软雅黑, Tahoma, Arial, sans-serif">, </span>TreeMap<span style="font-family:Microsoft Yahei, Hiragino Sans GB, Helvetica, Helvetica Neue, 微软雅黑, Tahoma, Arial, sans-serif">, </span>Hashtable and LinkedHashMap etc. The differences between the four are as follows (brief introduction):

HashMap: Our most commonly used Map, which stores data based on the HashCode value of the key, and its Value can be obtained directly based on the key. , and it has fast access speed. HashMap only allows the key value of one record to be Null (multiple records will be overwritten); it allows the Value of multiple records to be Null. Asynchronous.

TreeMap: It can sort the records it saves according to key. The default is in ascending order. You can also specify a sorting comparator. When using Iterator to traverse TreeMap, the records obtained are sorted. Out of order. TreeMap does not allow the key value to be null. Asynchronous.

Hashtable: Similar to HashMap, the difference is that neither key nor value is allowed to be null; it supports thread synchronization, that is, only one thread can write to Hashtable at any time. This also causes Hashtale to be slower when writing.

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

Online learning course sharing: java course

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 is a comparator interface that can sort collection objects or arrays. Sorting can be achieved by implementing the public compare(T o1,To2) method of this interface. This method is mainly based on the first parameter. o1, less than, equal to or greater than o2 returns a negative integer, 0 or a positive integer 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) {
                        // 降序排序
                        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));
        }
    }
}
Copy after login

The running results are as follows:

Implementation of Map sorting in java

The above example is to sort based on the key value of TreeMap, but sometimes we need to sort based on the value of TreeMap to sort. To sort values, we need to use the sort(List list, Comparator 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 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");
 
        //这里将map.entrySet()转换成list
        List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
        //然后通过比较器来实现排序
        Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
            //升序排序
            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()); 
          } 
    }
}
Copy after login

Running results

Implementation of Map sorting in java

HashMap

We are all HashMap values, there is no order, It is implemented according to the HashCode of the key. How do we implement sorting for this unordered HashMap? Referring to the value sorting of TreeMap, we can also implement the sorting 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>>() {
            //升序排序
            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()); 
          } 
     }
}
Copy after login

Running results:

Implementation of Map sorting in java

More related articles and tutorials are recommended:Getting started with java

The above is the detailed content of Implementation of Map sorting in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template