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)); } } }
The running results are as follows:
d:aaaaa c:bbbbb b:ccccc a:ddddd
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!