Java List排序
jopen
10年前
需求:对学生对象按照其 分数(降序)进行排序,当分数相同时按学号(从小到大)排序
实现:利用Collections类的 sort(List<T> list,Comparator<? super T> c) 方法,自定义比较器对象对指定对象进行排序
代码实现
Student类
class Student{ private int id; private String name; private float score; //成绩 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getScore() { return score; } public void setScore(float score) { this.score = score; } }比较器类
//先按成绩 降序 排序,如果成绩一样的话按id 升序 排序 class StudentComparator implements Comparator<Student>{ /** * return a negative integer, zero, or a positive integer as the first argument is less than, * equal to, or greater than the second. */ @Override public int compare(Student s1, Student s2) { if(s1.getScore()>s2.getScore()){ //greater return -1; }else if(s1.getScore()==s2.getScore()){ //equals if(s1.getId()>s2.getId()){ return 1; }else if(s1.getId()==s2.getId()){ return 0; }else{ return -1; } }else{ //less return 1; } } }Demo类
public class ListSortDemo { public static void main(String[] args) { Student s1 = new Student(); s1.setId(10001); s1.setName("cat"); s1.setScore(99.5f); Student s2 = new Student(); s2.setId(10008); s2.setName("bba"); s2.setScore(100.0f); Student s3 = new Student(); s3.setId(10011); s3.setName("bac"); s3.setScore(89.5f); List<Student> list = new ArrayList<Student>(); list.add(s1); list.add(s2); list.add(s3); System.out.println("排序之前-----------------------"); for(Student stu:list){ System.out.println("id="+stu.getId()+" name="+stu.getName()+" score="+stu.getScore()); } Collections.sort(list, new StudentComparator()); //排序 System.out.println("排序之后-----------------------"); for(Student stu:list){ System.out.println("id="+stu.getId()+" name="+stu.getName()+" score="+stu.getScore()); } } }
运行结果
排序之前-----------------------
id=10001 name=cat score=99.5
id=10008 name=bba score=100.0
id=10011 name=bac score=89.5
排序之后-----------------------
id=10008 name=bba score=100.0
id=10001 name=cat score=99.5
id=10011 name=bac score=89.5