Java map key value pairs sort by key and by value

I Theoretical preparation

Map is the collection interface of key value pairs. Its implementation classes mainly include HashMap, treemap, hashtable and LinkedHashMap.

Treemap: the implementation of navigablemap based on red black tree. The map is sorted according to the natural order of its keys, or according to the comparator provided when creating the map, depending on the construction method used.

The values of HashMap have no order. It is implemented according to the hashcode of key. How do we sort this unordered HashMap? Sort by referring to the value of treemap.

Map. Entry returns the collections view.

II Key sort

Treemap is in ascending order by default. If we need to change the sorting method, we need to use the comparator. Comparator is a comparator interface that can sort collection objects or arrays. The public compare (t O1, to2) method that implements this interface can realize sorting, as follows:

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
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("b","ccccc");
        map.put("d","aaaaa");
        map.put("c","bbbbb");
        map.put("a","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:aaaaa
c:bbbbb
b:ccccc
a:ddddd

III Value sort

The above example sorts according to the key value of treemap, but sometimes we need to sort according to the value of treemap. To sort values, we need to use the sort (list < T > list, comparator C) method of collections, which sorts the specified list according to the order generated by the specified comparator. However, there is a precondition that all elements must be able to be compared according to the provided comparator, as follows:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class TreeMapTest {
    public static void main(String[] args) {
        Map<String,String>();
        map.put("a","ddddd");
        map.put("c","bbbbb");
        map.put("d","aaaaa");
        map.put("b","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()); 
          } 
    }
}

The operation results are as follows:

d:aaaaa
c:bbbbb
b:ccccc
a:ddddd
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>