map<k,v> 对key排序
1 如果key为String类型 使用Treemap即可
TreeMap<String,Integer> p = new TreeMap<>();
p.put("desc",100);
p.put("cdn",1000);
p.put("hight",900);
p.put("about",60);
System.out.println(new Gson().toJson(p));
因为string实现了
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
2 如果key为对象类型比如 k , 让k实现
extends Comparable<? super V>>
public static <K extends Comparable<? super K>, V > Map<K, V> sortByKey(Map<K, V> map) {
Map<K, V> result = new LinkedHashMap<>();
Stream<Map.Entry<K, V>> st = map.entrySet().stream();
st.sorted (Comparator.comparing(e -> e.getKey() ))
.forEach(e -> result.put(e.getKey(), e.getValue()));
return result;
}