JAVA-List排序-Collections.sort()
当我们想对一个对象数组(集合)根据某一属性进行排序时,我们可以使用list中的Collection.sort(),这是一种较快捷的方式。
先放对象类型
public class Student {
String name;
double MathScore;
double EnglishScore;
public Student(String name, double mathScore, double englishScore) {
this.name = name;
MathScore = mathScore;
EnglishScore = englishScore;
}
@Override
public String toString() {
return "Student:" +
"姓名:'" + name + '\'' +
", MathScore=" + MathScore +
", EnglishScore=" + EnglishScore;
}
}
方法一:
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> stus = new ArrayList<Student>();
for(int i = 1;i <= 5;i++){
stus.add(new Student("student"+i,Math.random()*100,Math.random()*100));
/*随机生成五条学生对象用于接下来的排序*/
}
Collections.sort(stus, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if(o1.MathScore > o2.MathScore)
return 1;
else if(o1.MathScore<o2.MathScore)
return -1;
else
return 0;
/*这样是属于升序排列,如果要逆序,就互换return 1 和return -1的位置*/
}
});
for (Student a:stus) {
System.out.println(a.toString());
}
}
}
用Collections.sort()就比较快捷,但图上的方法写在主测试类里就显得不太简洁,所以comparator()还可以在Student类中实现,即继承Comparable接口,重写compareTo方法;
方法二:
public class Student implements Comparable<Student>{
String name;
double MathScore;
double EnglishScore;
public Student(String name, double mathScore, double englishScore) {
this.name = name;
MathScore = mathScore;
EnglishScore = englishScore;
}
@Override
public String toString() {
return "Student:" +
"姓名:'" + name + '\'' +
", MathScore=" + MathScore +
", EnglishScore=" + EnglishScore;
}
@Override
public int compareTo(Student o) {
if(this.MathScore > o.MathScore)
return 1;
else if(this.MathScore < o.MathScore)
return -1;
else
return 0;
}
}
public class Test {
public static void main(String[] args) {
List<Student> stus = new ArrayList<Student>();
for(int i = 1;i <= 5;i++){
stus.add(new Student("student"+i,Math.random()*100,Math.random()*100));
/*随机生成五条学生对象用于接下来的排序*/
}
Collections.sort(stus);
/*这样就简洁很多*/
for (Student a:stus) {
System.out.println(a.toString());
}
}
}
~~