TreeMap排序

实现TreeMap后默认为key升序排序,如果要实现key其他排序规则,可以使用Comparator对象作为参数,前提是key为可以排序的类型(String,int等类型)

1 Map<String,People> map = new TreeMap<>(new Comparator<String>() {
2     @Override
3     public int compare(final String o1, final String o2) {
4         return o2.compareTo(o1);
5     }
6 });

如果要实现TreeMap的value值排序,可以将Map转List后排序,在将排序后的List转回Map时,需要在toMap里增加LinkedHashMap::new,如果不指定LinkedHashMap,会使排序的效果丢失

 1 People people1 = new People("1","1");
 2 People people2 = new People("2","6");
 3 People people3 = new People("3","6");
 4 People people4 = new People("3","4");
 5 Map<String,People> map = new TreeMap<>();
 6 map.put("6",people1);
 7 map.put("9",people2);
 8 map.put("2",people3);
 9 map.put("1",people4);
10 //Map转List
11 List<Map.Entry<String,People>> entryList = new ArrayList<>(map.entrySet());
12 //排序List,按照value里的no字段升序排序
13 List<Map.Entry<String,People>> sortList = entryList.stream().sorted(Comparator.comparing(o1 -> o1.getValue().getNo())).collect(Collectors.toList()); 
14 //List转Map,不指定LinkedHashMap,当前sortMap排序效果会丢失,转后的Map默认按照key升序
15 Map<String,People> sortMap = sortList.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
16 //List转Map,指定LinkedHashMap::new,转后的Map排序效果仍然在
17 Map<String,People> sortMap1 = sortList.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(i1,i2)->i2,LinkedHashMap::new)); 
18 System.out.println("entryList:"+  JsonUtils.toJson(entryList));
19 System.out.println("sortList:"+  JsonUtils.toJson(sortList));
20 System.out.println("sortMap:"+  JsonUtils.toJson(sortMap));
21 System.out.println("sortMap1:"+  JsonUtils.toJson(sortMap1));
22 
23       
24 //People类
25 static class People{
26     public People(String no,String age) {
27         this.no = no;
28         this.age = age;
29     }
30     public String no;
31     public String age;
32 
33     public String getNo() {
34         return no;
35     }
36 
37     public String getAge() {
38         return age;
39     }
40 
41 }

 

 

posted @ 2024-02-16 14:45  leviH  阅读(35)  评论(0编辑  收藏  举报