Home  >  Article  >  Java  >  Detailed explanation of examples of sorting Map in Java

Detailed explanation of examples of sorting Map in Java

怪我咯
怪我咯Original
2017-07-02 10:38:021371browse

This article will share with you the issues of sorting by value and sorting by key in maps in Java, and through specific examples, I hope it will be helpful to everyone.

Types of Map

In Java, the main function of Map is to store key-value pairs. Since the value is obtained based on the key, duplicate keys are not allowed. It mainly has the following categories:

HashMap:

The most commonly used Map, it stores data according to the HashCode value of the key, and can be obtained directly according to the key Its value has a very fast access speed. When traversing, the order of obtaining data is completely random. HashMap only allows the key of one record to be Null at most; it allows the value of multiple records to be Null; HashMap does not support thread synchronization, that is, multiple threads can write HashMap at the same time at any time; this may lead to data inconsistency. If synchronization is required, you can use the synchronizedMap method of Collections to make the HashMap synchronized, or use ConcurrentHashMap. Hashtable is similar to HashMap. It inherits from the Dictionary class. The difference is that it does not allow the recorded keys or values ​​to be empty. It supports thread synchronization, that is, only one thread can write to the Hashtable at any time, so it also causes the Hashtable to be written. The timing will be slower.

LinkedHashMap

saves the insertion order of records. When using Iterator to traverse LinkedHashMap, the record obtained first must be inserted first. Also You can use parameters during construction and sort by the number of applications. It will be slower than HashMap when traversing, but there is an exception. When HashMap has a large capacity and the actual data is small, the traversal may be slower than LinkedHashMap, because the traversal speed of LinkedHashMap is only related to the actual data and has nothing to do with the capacity. The traversal speed of HashMap is related to its capacity.

TreeMap

Implements SortMap interface, which can sort the records it saves by key. The default is by key value Sorting in ascending order, you can also specify the sorting comparator. When using Iterator to traverse the TreeMap, the records obtained are sorted.

Sort by key

From the above introduction of Map types, we can see that TreeMap has its own key sorting function, which only needs to be sorted when creating Just implement a Compare interface at the same time. The example is as follows:

private static void sort_by_key(){
    Map<Integer, Integer> treeMap = new TreeMap<>(new Comparator<Integer>() {
      @Override
      public int compare(Integer o1, Integer o2) {
        return o2-o1; //倒序.这里说明一下,如果返回负值,则o1先输出,反之则o2
      }
    });
    
    //填充数据
    for(int i = 0; i < 100;i++){
      int key = (int)(10000*Math.random());
      int value = (int)(10000*Math.random());
      treeMap.put(key, value);
    }
    outMap(treeMap);
  }

public static void outMap(Map<Integer, Integer> map){
    for(Integer integer:map.keySet()){
      System.out.println("key="+integer+"  value="+map.get(integer));
    }
}
/* 结果如下:
key=9977  value=80
key=9684  value=7108
key=9422  value=1706
key=9264  value=1210
key=9248  value=4758
key=9024  value=7048
key=8892  value=3124
key=8879  value=6414
key=8814  value=8171
key=8728  value=1538
key=8513  value=4956
key=8462  value=5617
key=8355  value=8912
*/

As can be seen from the above, sorting by key is not difficult, but placement sorting is more troublesome, and the Map needs to be transferred.

Sort by value

Since Map in Java does not have this function, we need to implement it ourselves. The idea is as follows:

List in Java can use the compare interface.
Map is actually a collection of Entrya8093152e673feb7aba1828c43532094
So you can use List to achieve sorting
Insert the sorted elements into LinkedMap

The code is implemented as follows:

 private static Map<Integer, Integer> sortMap(Map<Integer, Integer> linkedMap) {
    
    List<Map.Entry<Integer, Integer>> cache = new ArrayList<>(linkedMap.entrySet());

    //重写比较函数
    Collections.sort(cache,new Comparator<Map.Entry<Integer, Integer>>() {
      @Override
      public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
        //若返回值小于0,则o1在o2前面
        return o2.getValue()-o1.getValue();
      }
    });

    Map<Integer, Integer> resultMap = new LinkedHashMap<>();
    //将结果插入LinkedMap然后返回
    for(int i = 0; i < cache.size();i++){
      resultMap.put(cache.get(i).getKey(), cache.get(i).getValue());
    }
    return resultMap;
  }
/*结果:
7965  9966
1067  9963
1720  9833
3257  9738
3934  9578
777  9348
1924  9315
3472  9270
3649  9114
5892  9078
*/

In this way, sorting by value and sorting by key can be implemented.

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

Statement:
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