Home > Java > Javagetting Started > Can Java sort the keys of a map?

Can Java sort the keys of a map?

(*-*)浩
Release: 2019-11-19 11:52:55
Original
2159 people have browsed it

Can Java sort the keys of a map?

Map is a collection interface of key-value pairs. Its implementation classes mainly include: HashMap, TreeMap, Hashtable and LinkedHashMap, etc. (Recommended learning: java course)

TreeMap: NavigableMap implementation based on red-black tree (Red-Black tree), the map is sorted according to the natural order of its keys, or based on the creation of a map The Comparator provided is sorted, depending on the constructor used.

Map.Entry returns the Collections view.

key sorting

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. Implementing the public compare(T o1, To2) method of this interface can achieve 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));
        }
    }
}
Copy after login

The running results are as follows:

d:aaaaa
c:bbbbb
b:ccccc
a:ddddd
Copy after login

The above is the detailed content of Can Java sort the keys of a map?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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