Java集合排序(看完秒懂)

比如将一个List<Student>排序,则有两种方式:
1:Student实现Comparable接口:
2:给排序方法传递一个Comparator参数:

请看下面的举例:
Student类:

package demo;

//Student实现Comparable,需要实现compareTo方法
public class Student implements Comparable<Student>{
    private String name;
    private Integer age;

    public Student(String name,Integer age) {
        // TODO Auto-generated constructor stub
        this.name=name;
        this.age=age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public int compareTo(Student o) {
        // TODO Auto-generated method stub
        if(this.age>o.getAge()){
            return 1;
        }
        else if(this.age<o.getAge()){
            return -1;
        }
        else{
            return 0;
        }
    }
}

主类:

package demo;

import java.util.*;

public class main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List<Student> list=new ArrayList<Student>();
        Student s1=new Student("T-F", 18);
        Student s2=new Student("H胡歌", 28);
        Student s3=new Student("Z周润发", 50);
        Student s4=new Student("M梅兰芳", 100);
        list.add(s1);
        list.add(s4);
        list.add(s3);
        list.add(s2);
        
        Iterator iterator=list.iterator();
        System.out.println("------默认排序(按年纪)-------");
        Collections.sort(list);
        while(iterator.hasNext()){
            Student s=(Student)iterator.next();
            System.out.println(s.getName()+" "+s.getAge());
        }
        
        System.out.println("------倒序排序-------");
        Comparator comparator=Collections.reverseOrder();
        Collections.sort(list,comparator);
        Iterator iterator_reverse=list.iterator();
        while(iterator_reverse.hasNext()){
            Student s=(Student)iterator_reverse.next();
            System.out.println(s.getName()+" "+s.getAge());
        }
        
        System.out.println("------根据姓名排序-------");
        Collections.sort(list,new Comparator<Student>(){
            @Override
            public int compare(Student o1, Student o2) {
                // TODO Auto-generated method stub
                return    o1.getName().compareTo(o2.getName());
            }}
        );
        Iterator iterator_name=list.iterator();
        while(iterator_name.hasNext()){
            Student s=(Student)iterator_name.next();
            System.out.println(s.getName()+" "+s.getAge());
        }
        
    }
}
执行结果:

------默认排序-------
T-F 18
H胡歌 28
Z周润发 50
M梅兰芳 100
------倒序排序-------
M梅兰芳 100
Z周润发 50
H胡歌 28
T-F 18
------根据姓名排序-------
H胡歌 28
M梅兰芳 100
T-F 18
Z周润发 50

猜你喜欢

转载自blog.csdn.net/youjin/article/details/81390513