Java中Collections.sort()的用法

Java中Collections.sort()的使用:

在日常开发中,很多时候都需要对一些数据进行排序的操作。然而那些数据一般都是放在一个集合中如:Map ,Set ,List 等集合中。他们都提共了一个排序方法 sort(),要对数据排序直接使用这个方法就行,但是要保证集合中的对象是可比较的。

怎么让一个对象是 可比较的,那就需要该对象实现 Comparable<T> 接口啦。然后重写里面的
compareTo()方法。我们可以看到Java中很多类都是实现类这个接口的 如:Integer,Long 等等。。。

假设我们有一个学生类,默认需要按学生的年龄字段 age 进行排序 代码如下:

public class Student implements Comparable<Student> { private int id; private int age; private String name; public Student(int id, int age, String name) { this.id = id; this.age = age; this.name = name; } @Override public int compareTo(Student o) { //降序 //return o.age - this.age; //升序 return this.age - o.age; } @Override public String toString() { return "Student{" + "id=" + id + ", age=" + age + ", name='" + name + '\'' + '}'; } } 

这里说一下重写的 public int compareTo(Student o){} 这个方法,它返回三种 int 类型的值: 负整数,零 ,正整数。

 


测试代码:

public static void main(String args[]){ List<Student> list = new ArrayList<>(); list.add(new Student(1,25,"关羽")); list.add(new Student(2,21,"张飞")); list.add(new Student(3,18,"刘备")); list.add(new Student(4,32,"袁绍")); list.add(new Student(5,36,"赵云")); list.add(new Student(6,16,"曹操")); System.out.println("排序前:"); for (Student student : list) { System.out.println(student.toString()); } //使用默认排序 Collections.sort(list); System.out.println("默认排序后:"); for (Student student : list) { System.out.println(student.toString()); } } 

输出日志:

排序前:
Student{id=1, age=25, name='关羽'}
Student{id=2, age=21, name='张飞'}
Student{id=3, age=18, name='刘备'}
Student{id=4, age=32, name='袁绍'}
Student{id=5, age=36, name='赵云'} Student{id=6, age=16, name='曹操'} 默认排序后: Student{id=6, age=16, name='曹操'} Student{id=3, age=18, name='刘备'} Student{id=2, age=21, name='张飞'} Student{id=1, age=25, name='关羽'} Student{id=4, age=32, name='袁绍'} Student{id=5, age=36, name='赵云'} 

比较器的使用:

这个时候需求又来了,默认是用 age 排序,但是有的时候需要用 id 来排序怎么办? 这个时候比较器 :Comparator 就排上用场了。

Comparator 的使用有两种方式:

Collections.sort(list,Comparator<T>);
list.sort(Comparator<T>);
其实主要是看 Comparator 接口的实现,重写里面的 compare 方法。代码如下:

//自定义排序1
Collections.sort(list, new Comparator<Student>() {
    @Override
    public int compare(Student o1, Student o2) { return o1.getId() - o2.getId(); } }); 

compare(Student o1, Student o2) 方法的返回值跟 Comparable<> 接口中的 compareTo(Student o) 方法 返回值意思相同。另一种写法如下:

//自定义排序2
list.sort(new Comparator<Student>() {
    @Override
    public int compare(Student o1, Student o2) { return o1.getId() - o2.getId(); } }); 

输出日志:

排序前:
Student{id=1, age=25, name='关羽'}
Student{id=2, age=21, name='张飞'}
Student{id=3, age=18, name='刘备'}
Student{id=4, age=32, name='袁绍'}
Student{id=5, age=36, name='赵云'} Student{id=6, age=16, name='曹操'} 自定义排序后: Student{id=1, age=25, name='关羽'} Student{id=2, age=21, name='张飞'} Student{id=3, age=18, name='刘备'} Student{id=4, age=32, name='袁绍'} Student{id=5, age=36, name='赵云'} Student{id=6, age=16, name='曹操'} 

欢迎关注微信公众号“Java面试达人”,(id:javasuperman),收看更多精彩内容

 

猜你喜欢

转载自www.cnblogs.com/javasuperman/p/10705927.html