Java初学习-List中的排序

第一种方法,就是List中对象的类定义里实现Comparable接口,再通过Collectons.sort调用,代码如下:

public class Person implements Comparable<Person> {
    private String name;
    private Integer order; //Interger object, not int variable
    
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Integer getOrder() {
        return order;
    }
 
    public void setOrder(Integer order) {
        this.order = order;
    }
 
    @Override
    public int compareTo(Person arg0) {
        return this.getOrder().compareTo(arg0.getOrder());
    }
}
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);
    for (Person p : listA) {
        System.out.println(p.getName());
    }
}

第二种方法,重载Collections.sort方法,通过一个匿名内部类实现一个compare()实现排序

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


你可能感兴趣的:(Java初学习-List中的排序)