對List進行多維度排序

在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();
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章