java中的map对键值的排序
public static void main(String[] args) {
mapSort();
}
public static void mapSort()
{
System.out.println("方法一");
// 方法一 初始的排序方法
//可以在初始化的时候加入比较器对键 进行排序
Map map = new TreeMap(
new Comparator() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
);
map.put("a", "aaaaa");
map.put("d", "ddddd");
map.put("b", "bbbbb");
map.put("c", "ccccc");
// entryset 返回所有的键值映射关系成员
// 实现对value 的排序
//这里将map.entrySet()转换成list 对值进行排序
List> list = new ArrayList>(map.entrySet());
//然后通过比较器来实现排序
Collections.sort(list,new Comparator>() {
//升序排序
public int compare(Map.Entry o1,
Map.Entry o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
for(Map.Entry mapping:list){
System.out.println(mapping.getKey()+":"+mapping.getValue());
}
System.out.println("方法二");
//方法二 java8 新特性
// 创建一个Map,并填入数据
Map codes = new HashMap<>();
codes.put("United States", 1);
codes.put("Germany", 49);
codes.put("France", 33);
codes.put("China", 86);
codes.put("Pakistan", 92);
// 按照Map的键进行排序
Map sortedMap = codes.entrySet().stream()
//按照键进行排序
.sorted(Map.Entry.comparingByKey())
.collect(
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldVal, newVal) -> oldVal,
linkedHashMap::new
)
);
// 将排序后的Map打印
sortedMap.entrySet().forEach(System.out::println);
//对map的值进行排序
Map sortedMap2 = codes.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldVal, newVal) -> oldVal,
linkedHashMap::new)
);
sortedMap2.entrySet().forEach(System.out::println);
}