并列排名的實現(xiàn)

import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;


class Student {
    private String name;
    private double score;
    private int age;
    private int index;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Student(String name, double score, int age) {
        this.name = name;
        this.score = score;
        this.age = age;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", score=" + score +
                ", age=" + age +
                ", index=" + index +
                '}';
    }
}

class TestDemo {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
                new Student("Jack", 52, 10),
                new Student("Amdy", 79.5, 10),
                new Student("Lucy", 68, 9),
                new Student("Tom", 79.5, 11),
                new Student("Jerry", 52, 8),
                new Student("Cherry", 79.5, 10),
                new Student("Sweet", 91, 12),
                new Student("Lucky", 68, 9),
                new Student("Sim", 79.5, 10),
                new Student("Solem", 65, 10)
        );
        // fun1(students);
        // System.out.println("---------------分割線---------------------");
        // fun2(students);
        // System.out.println("---------------分割線---------------------");
        // fun3(students);
        // System.out.println("---------------分割線---------------------");
        func4(students);
    }

    /**
     * 按照成績排序 ---低級寫法
     */
    public static void fun1(List<Student> students) {
        students.sort((s1, s2) -> -Double.compare(s1.getScore(), s2.getScore()));
        int index = 0;
        double lastScore = -1;

        for (Student s : students) {
            if (Double.compare(lastScore, s.getScore()) != 0) {
                lastScore = s.getScore();
                index++;
            }
            System.out.println("名次:" + index + "\t分數(shù)" + s.getScore() + "\t名字" + s.getName());
        }
    }

    /**
     * 按照成績排序 --- 使用Java 8
     */
    public static void fun2(List<Student> students) {
        List<Entry<Double, List<Student>>> list = students.stream()
                .collect(Collectors.groupingBy(Student::getScore))
                .entrySet()
                .stream()
                .sorted((s1, s2) -> -Double.compare(s1.getKey(), s2.getKey()))
                .collect(Collectors.toList());
        int index = 1;
        for (Entry<Double, List<Student>> entry : list) {
            System.out.print("名次:" + index + "\t分數(shù):" + entry.getKey() + "\t名字");
            entry.getValue().forEach((s) -> System.out.print("  " + s.getName()));
            System.out.println();
            index++;
        }
    }

    /**
     * 按照成績排序 --- 使用Java 8切蟋;并列排名跳到下一名
     */
    public static void fun3(List<Student> students) {
        List<Entry<Double, List<Student>>> list = students.stream()
                .collect(Collectors.groupingBy(Student::getScore))
                .entrySet()
                .stream()
                .sorted((s1, s2) -> -Double.compare(s1.getKey(), s2.getKey()))
                .collect(Collectors.toList());
        int index = 1;
        for (Entry<Double, List<Student>> entry : list) {
            System.out.print("名次:" + index + "\t分數(shù):" + entry.getKey() + "\t名字");
            entry.getValue().forEach((s) -> System.out.print("  " + s.getName()));
            System.out.println();
            index = index + entry.getValue().size();
        }
    }

    /**
     * 按照多條件排序 --- 使用Java 8坐漏;并列排名跳到下一名
     */
    public static void func4(List<Student> students) {
        // students.sort((h1, h2) -> {
        //     // 排名相同苫幢,年齡正序排序
        //     if (Double.compare(h1.getScore(), h2.getScore()) == 0) {
        //         return Double.compare(h1.getAge(), h2.getAge());
        //     }
        //     return -Double.compare(h1.getScore(), h2.getScore());
        // });
        students.sort(Comparator.comparing(Student::getScore).reversed().thenComparing(Student::getAge));
        // students.forEach(System.out::println);
        int index = 0;
        int count = 0;
        double lastScore = -1;
        Map<Integer, Student> rankMap = new HashMap<>(5);
        for (int i = 0; i < students.size(); i++) {
            Student s = students.get(i);
            System.out.println(s.toString() + ",lastScore:" + lastScore + "图张,count:" + count + "锋拖,index:" + index);
            // 如果成績和上一名的成績不相同,那么排名+1
            if (Double.compare(lastScore, s.getScore()) != 0) {
                lastScore = s.getScore();
                index = index + 1 + count;
                count = 0;
            } else {
                // 分數(shù)相同诈悍,如果年齡不同,排名+1
                if (Double.compare(students.get(i - 1).getAge(), s.getAge()) != 0) {
                    index = index + 1 + count;
                    count = 0;
                } else {
                    // 重復(fù)數(shù)+1
                    count++;
                }
            }
            s.setIndex(index);
            System.out.println(s.toString() + "兽埃,lastScore:" + lastScore + "侥钳,count:" + count + ",index:" + index);
            System.out.println("****************");
            rankMap.put(i, s);
        }
        for (Integer key : rankMap.keySet()) {
            System.out.println(rankMap.get(key));
        }
    }

}

最后面貼出并列排名跳到下一名的運行結(jié)果柄错,index即是各個學(xué)生的排名舷夺。


其實如果List<Student> students參數(shù)是從數(shù)據(jù)庫中讀取的,可以通過sql進行一遍排序售貌,

select name, score, age from tb_student order by score desc,age asc; 

來替代java排序

students.sort(Comparator.comparing(Student::getScore).reversed().thenComparing(Student::getAge));

然后代碼里面不再排序给猾,只做并列排名計算名次跳到下一名的特殊處理。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末颂跨,一起剝皮案震驚了整個濱河市敢伸,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌恒削,老刑警劉巖池颈,帶你破解...
    沈念sama閱讀 217,509評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異钓丰,居然都是意外死亡躯砰,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評論 3 394
  • 文/潘曉璐 我一進店門携丁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來琢歇,“玉大人,你說我怎么就攤上這事梦鉴】笪ⅲ” “怎么了?”我有些...
    開封第一講書人閱讀 163,875評論 0 354
  • 文/不壞的土叔 我叫張陵尚揣,是天一觀的道長。 經(jīng)常有香客問我掖举,道長快骗,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,441評論 1 293
  • 正文 為了忘掉前任塔次,我火速辦了婚禮方篮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘励负。我一直安慰自己藕溅,他們只是感情好,可當我...
    茶點故事閱讀 67,488評論 6 392
  • 文/花漫 我一把揭開白布继榆。 她就那樣靜靜地躺著巾表,像睡著了一般汁掠。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上集币,一...
    開封第一講書人閱讀 51,365評論 1 302
  • 那天考阱,我揣著相機與錄音,去河邊找鬼鞠苟。 笑死乞榨,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的当娱。 我是一名探鬼主播吃既,決...
    沈念sama閱讀 40,190評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼跨细!你這毒婦竟也來了鹦倚?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,062評論 0 276
  • 序言:老撾萬榮一對情侶失蹤扼鞋,失蹤者是張志新(化名)和其女友劉穎申鱼,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體云头,經(jīng)...
    沈念sama閱讀 45,500評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡捐友,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,706評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了溃槐。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片匣砖。...
    茶點故事閱讀 39,834評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖昏滴,靈堂內(nèi)的尸體忽然破棺而出猴鲫,到底是詐尸還是另有隱情,我是刑警寧澤谣殊,帶...
    沈念sama閱讀 35,559評論 5 345
  • 正文 年R本政府宣布拂共,位于F島的核電站,受9級特大地震影響姻几,放射性物質(zhì)發(fā)生泄漏宜狐。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,167評論 3 328
  • 文/蒙蒙 一蛇捌、第九天 我趴在偏房一處隱蔽的房頂上張望抚恒。 院中可真熱鬧,春花似錦络拌、人聲如沸俭驮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽居触。三九已至搬味,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間譬圣,已是汗流浹背瓮恭。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留厘熟,地道東北人屯蹦。 一個月前我還...
    沈念sama閱讀 47,958評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像绳姨,于是被迫代替她去往敵國和親登澜。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,779評論 2 354