1、根据key排序
public static void main(String[] args) {
Map<String, String> map = new HashMap<>(3);
map.put("ccc", "ccc");
map.put("aaa", "aaa");
map.put("bbb", "bbb");
// 注意:这里不能用HashMap存,HashMap的遍历顺序是随机的
// Collectors.toMap()默认是HashMap
TreeMap<String, String> result = map.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getKey))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (k1, k2) -> k1, TreeMap::new));
System.out.println("result: " + result);
}
输出结果:
2、根据value排序
public static void main(String[] args) {
Map<String, String> map = new HashMap<>(3);
map.put("ccc", "ccc");
map.put("aaa", "aaa");
map.put("bbb", "bbb");
// 注意:这里不能用HashMap存,HashMap的遍历顺序是随机的
// Collectors.toMap()默认是HashMap
TreeMap<String, String> result = map.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, TreeMap::new));
System.out.println("result: " + result);
}
输出结果: