浅谈java中的TreeMap 排序与TreeSet 排序

时间:2021-12-11 02:05:56

TreeMap

java" id="highlighter_673763">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com;
 
import java.util.Comparator;
import java.util.TreeMap;
 
public class Test5 {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TreeMap<String, String> tree = new TreeMap<String, String>(
                new Comparator<Object>() {
                    @Override
                    public int compare(Object o1, Object o2) {
                        // TODO Auto-generated method stub
                        if(o1 == null || o2 == null){
                            return 0;
                        }
                        
                        return o1.toString().compareTo(o2.toString());
                    }
                }
        );
                
        
        tree.put("k", "1");
        tree.put("ba", "2");
        tree.put("z", "3");
        tree.put("d", "4");
        tree.put("e", "5");
        tree.put("an", "6");
        tree.put("c", "7");
        
        for(String str : tree.keySet()){
            System.out.println(str);
        }
    }
}

经测试默认是按照 KEY 进行排序的。

但是可以写对象比较器,进行自定义排序。

TreeSet : 自定义倒序排序,默认按照正序排序,1,2,3,4,5,6

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com;
 
import java.util.Comparator;
import java.util.TreeSet;
 
public class Test6 {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TreeSet<Object> tree = new TreeSet<Object>(new Comparator<Object>() {
 
            @Override
            public int compare(Object o1, Object o2) {
                // TODO Auto-generated method stub
                if(o1 == null || o2 == null){
                    return 0;
                }
                
                if(Integer.parseInt(o1.toString()) > Integer.parseInt(o2.toString())){
                    return -1;
                }else if(Integer.parseInt(o1.toString()) < Integer.parseInt(o2.toString())){
                    return 1;
                }else{
                    return 0;
                }
            }
        });
        
        tree.add(4);
        tree.add(5);
        tree.add(6);
        tree.add(1);
        tree.add(2);
        tree.add(3);
 
        for(Object o : tree){
            System.out.println(o);
        }
    }
 
}

以上这篇浅谈java中的TreeMap 排序与TreeSet 排序就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。