对List进行多维度排序

来源:互联网 发布:mac 磁盘被锁定怎么装 编辑:程序博客网 时间:2024/05/09 18:01

在java中,如果要对集合对象或数组对象进行排序,需要实现Comparator接口以达到我们想要的目标。

1 实体类

package domain;/** * Created by Johny on 2016/8/31. */public class Student {    /**     * 学号     */    int id ;    /**     * 分数     */    int score;    public Student(int id, int score) {        this.id = id;        this.score = score;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public int getScore() {        return score;    }    public void setScore(int score) {        this.score = score;    }}

二、实现Comparator接口

package service;import domain.Student;import java.util.Comparator;/** * Created by Johny on 2016/8/31. * 通过实现Comparator接口对List集合进行多维度排序 * 举例:对学生的成绩进行排名,成绩相同的按照学号大小排序 */public class SortUtilForList implements Comparator<Object> {    /**     * 为学生进行排名     * @param o1     * @param o2     * @return     */    @Override    public int compare(Object o1, Object o2) {        if (o1 instanceof Student){            if (((Student) o1).getScore() != ((Student)o2).getScore()){                // 如果学生的分数不同,按照分数进行排名                return compareWithScore(((Student) o1).getScore(),((Student)o2).getScore());            }else {                // 如果学生的分数相同按照学号进行排名                return compareWithId(((Student) o1).getId(), ((Student) o2).getId());            }        }        return 0;    }    /**     * 通过学生的学号进行排序     * @param id1     * @param id2     * @return     */    private int compareWithId(int id1, int id2) {        if (id1 > id2){            return -1;        }        return 1;    }    /**     * 通过学生的分数进行排序     * @param score1     * @param score2     * @return     */    private int compareWithScore(int score1, int score2) {        if (score1 > score2){            return -1;        }        return 1;    }}

三、测试

package service;import domain.Student;import org.junit.Test;import java.util.ArrayList;import java.util.Collections;import java.util.List;import static org.junit.Assert.*;public class SortUtilForListTest {    @Test    public void testCompare() throws Exception {        SortUtilForList sortUtilForList = new SortUtilForList();        List<Student> students = new ArrayList<Student>();        students.add(new Student(1,88));        students.add(new Student(3,98));        students.add(new Student(4,88));        students.add(new Student(2,78));        students.add(new Student(6,68));        students.add(new Student(5,88));        Collections.sort(students, sortUtilForList);        students.toString();    }}


1 0
原创粉丝点击