排序HashMap中的key
import java.util.*;
/**
* HashMap转换成TreeMap
* @author BadCode
* @date 2019/9/26 23:26
*/
public class HashMapToTreeMap {
public static void main(String[] args) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("Add","Java");
hashMap.put("Dogwe","Python");
hashMap.put("Cweool","Go");
hashMap.put("Elsde","Html");
hashMap.put("BadCoder","C#");
//hashMap遍历
traverseMap(hashMap);
System.out.println("**************");
//hashMap转换成,TreeMap默认是按照Key值升序排序的
TreeMap<String, String> treeMap = new TreeMap<>(hashMap);
//treeMap遍历
traverseMap(treeMap);
}
private static void traverseMap(Map<String, String>... maps) {
for (Map<String, String> map : maps) {
Set<Map.Entry<String, String>> set = map.entrySet();
for (Map.Entry<String, String> entry : set) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
}
运行结果
Add:Java
Elsde:Html
BadCoder:C#
Dogwe:Python
Cweool:Go
**************
Add:Java
BadCoder:C#
Cweool:Go
Dogwe:Python
Elsde:Html