码迷,mamicode.com
首页 > 编程语言 > 详细

Java中List的排序

时间:2016-03-13 10:09:17      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

第一种方法,就是list中对象实现Comparable接口,代码如下:

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
public class Person implements Comparable<Person> {
    private String name;
    private Integer order;
 
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
 
    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
 
    /**
     * @return the order
     */
    public Integer getOrder() {
        return order;
    }
 
    /**
     * @param order
     *            the order to set
     */
    public void setOrder(Integer order) {
        this.order = order;
    }
 
    @Override
    public int compareTo(Person arg0) {
        return this.getOrder().compareTo(arg0.getOrder());
    }
 
}

 

 

第二种方法,就是在重载Collections.sort方法,代码如下:

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
public class Person {
    private String name;
    private Integer order;
 
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
 
    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
 
    /**
     * @return the order
     */
    public Integer getOrder() {
        return order;
    }
 
    /**
     * @param order
     *            the order to set
     */
    public void setOrder(Integer order) {
        this.order = order;
    }
 
}

 

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
public static void main(String[] args) {
        List<Person> listA = new ArrayList<Person>();
        Person p1 = new Person();
        Person p2 = new Person();
        Person p3 = new Person();
 
        p1.setName("name1");
        p1.setOrder(1);
        p2.setName("name2");
        p2.setOrder(2);
        p3.setName("name3");
        p3.setOrder(3);
 
        listA.add(p2);
        listA.add(p1);
        listA.add(p3);
         
        Collections.sort(listA, new Comparator<Person>() {
            public int compare(Person arg0, Person arg1) {
                return arg0.getOrder().compareTo(arg1.getOrder());
            }
        });
         
        for (Person p : listA) {
            System.out.println(p.getName());
        }
    }

 

两次执行的结果都是:

name1

name2

name3

Java中List的排序

标签:

原文地址:http://www.cnblogs.com/litao0505/p/5271257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!