List集合中的元素排序

java.util.collections中的sort方法实现了对集合中的数据进行排序


1、Collections.sort(List<T> list)

List集合中的元素排序


要清楚一点就是,sort(List<T> list) 中的T必须是实现了Comparable<T>接口,重写compareTo()方法。

(该方法的返回值:0代表相等,大于0代表大于,小鱼0代表小于)

上面例子中的Integer类,java自己已经实现了Comparable<T>接口,就不需要我们去实现了,如果在我们

自己定义的类中,一定要实现Comparable<T>接口,重写compareTo()方法。java中还有很多对Comparable<T>

接口的重写,具体可以查看API手册。


下面是一个重写compareTo()方法的一个小例子

package ListSortDemo;

public class Student implements Comparable<Student> {
private int score;
private int age;

public Student(int score, int age) {
super();
this.score = score;
this.age = age;
}

public int getScore(){
return score;
}
public int getAge(){
return age;
}


@Override
public String toString() {
return "Student [score=" + score + ", age=" + age + "]";
}


@Override
public int compareTo(Student s) {
int a = this.score - s.score;

if(a==0){
return this.age - s.age;
}
return a;
}
}


package ListSortDemo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class SortDemo {
public static void main(String[] args){
List<Student> students = new ArrayList<Student>();

students.add(new Student(98,23));
students.add(new Student(94,22));
students.add(new Student(95,24));
students.add(new Student(94,21));

Collections.sort(students);
for(Student s: students){
System.out.println(s);
}
}
}

运行结果:

Student [score=94, age=21]
Student [score=94, age=22]
Student [score=95, age=24]
Student [score=98, age=23]


除了以上的排序外,往往更多用到的是按照规则排序,


2、Collections.sort(List<T> list,Comparator<? super T>c)  此方法比上面的方法多了一个参数,称为比较器

根据比较器产生的顺序对指定列表进行排序。


package ListSortDemo01;


public class Student{
private int score;
private int age;

public Student(int score, int age) {
super();
this.score = score;
this.age = age;
}

public int getScore(){
return score;
}
public int getAge(){
return age;
}


@Override
public String toString() {
return "Student [score=" + score + ", age=" + age + "]";
}
}


package ListSortDemo01;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class Test {
public static void main(String[] args){
List<Student> students = new ArrayList<Student>();

students.add(new Student(98,23));
students.add(new Student(94,22));
students.add(new Student(95,24));
students.add(new Student(94,21));

for(Student s: students){
System.out.println(s);
}
System.out.println("排序之后");
Collections.sort(students,new Comparator<Student>(){
public int compare(Student o1,Student o2){
int a = o1.getScore() - o2.getScore();
if(a == 0){
return o1.getAge() - o2.getAge();
}
return a;
}
});
for(Student s: students){
System.out.println(s);
}
}
}


运行结果:

Student [score=98, age=23]
Student [score=94, age=22]
Student [score=95, age=24]
Student [score=94, age=21]
排序之后
Student [score=94, age=21]
Student [score=94, age=22]
Student [score=95, age=24]
Student [score=98, age=23]


这个方法不需要实现Comparable<T>接口,比较器就是对Comparator<T>接口的实现,

必须重写里面的compare(T o1,T o2)方法。


以上就是LIst集合的两种排序方式,如有不妥,多多指出。