Java案例使用比較排序器comparator實現成績排序
更新時間:2022年04月01日 10:43:04 作者:再美不及姑娘你
這篇文章主要介紹了Java案例使用比較排序器comparator實現成績排序,主要通過案例用TreeSet集合存儲多個學生信息,并遍歷該集合,要按照總分從高到低進行排序,下文介紹需要的朋友可以參考一下
需求:用TreeSet集合存儲多個學生信息(姓名,語文成績,數學成績),并遍歷該集合;要按照總分從高到低進行排序
分析:
- 1.創(chuàng)建學生類 成員變量 姓名,語文成績、數學成績;成員方法 求總分;構造方法 無參構造,帶參構造;
get\set方法 - 2.創(chuàng)建測試類
- 3.創(chuàng)建
TreeSet集合對對象,并使用內部類的方式重寫compare方法
要定好排序規(guī)則,主要條件按照總分從高到底排序,在總分相同的情況下按照語文成績排序,在兩者都相同的情況下判斷姓名是否相同,相同就不存儲,不相同存進來,按照姓名字母進行排序
- 4.創(chuàng)建學生對象,并使用帶參構造添加學生數據
- 5.使用
add方法將學生數據加入到TreeSet集合中 - 6.進行遍歷
代碼實現:
Student類
public class Student {
? //成員變量
? private String name;
? private int YWscore;
? private int YYscore;
?
? //構造方法
? public Student(){}
?
? public Student(String name, int YWscore, int YYscore) {
? ? ? this.name = name;
? ? ? this.YWscore = YWscore;
? ? ? this.YYscore = YYscore;
? }
? //get/set方法
?
? public String getName() {
? ? ? return name;
? }
?
? public void setName(String name) {
? ? ? this.name = name;
? }
?
? public int getYWscore() {
? ? ? return YWscore;
? }
?
? public void setYWscore(int YWscore) {
? ? ? this.YWscore = YWscore;
? }
?
? public int getYYscore() {
? ? ? return YYscore;
? }
?
? public void setYYscore(int YYscore) {
? ? ? this.YYscore = YYscore;
? }
? //定義求總成績方法
? public int getSum(){
? ? ? int sum=YWscore+YYscore;
? ? ? return sum;
? }
}
?測試類
public class StudentDemo {
? public static void main(String[] args) {
? ? ? //創(chuàng)建TreeSet集合對象
? ? ? TreeSet<Student>ts=new TreeSet<Student>(new Comparator<Student>() {
? ? ? ? ? @Override
? ? ? ? ? public int compare(Student s1, Student s2) {
// ? ? ? ? ? ? ? return 0;
? ? ? ? ? ? ? int num=s2.getSum()-s1.getSum();//要從高到底排序
? ? ? ? ? ? ? int num1= num==0?s1.getYWscore()-s2.getYWscore():num;//當總分相同時按照語文成績排序
? ? ? ? ? ? ? int num2= num1==0?s1.getName().compareTo(s2.getName()):num1;
? ? ? ? ? ? ? return num2;
? ? ? ? ? }
? ? ? });
? ? ? //創(chuàng)建學生對象
? ? ? Student s1=new Student("張三",56,66);
? ? ? Student s2=new Student("張四",70,69);
? ? ? Student s3=new Student("張五",80,76);
? ? ? Student s4=new Student("張六",66,96);
? ? ? Student s5=new Student("張七",66,96);
? ? ? ts.add(s5);
? ? ? ts.add(s1);
? ? ? ts.add(s2);
? ? ? ts.add(s3);
? ? ? ts.add(s4);
? ? ? //遍歷
? ? ? for (Student ss:ts){
? ? ? ? ? System.out.println(ss.getName()+","+ss.getYWscore()+","+ss.getYYscore()+","+ss.getSum());
? ? ? }
? }
}到此這篇關于Java案例使用比較排序器comparator實現成績排序的文章就介紹到這了,更多相關comparator實現成績排序內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot中使用MyBatis-Plus實現分頁接口的詳細教程
MyBatis-Plus是一個MyBatis的增強工具,在MyBatis的基礎上只做增強不做改變,為簡化開發(fā)、提高效率而生,在SpringBoot項目中使用MyBatis-Plus可以大大簡化分頁邏輯的編寫,本文將介紹如何在 SpringBoot項目中使用MyBatis-Plus實現分頁接口2024-03-03
JavaScript 與 Java 區(qū)別介紹 學java怎么樣
JavaScript 是一種嵌入式腳本文件,直接插入網頁,有瀏覽器一邊解釋一邊執(zhí)行。而java 語言不一樣,他必須在JAVA虛擬機上運行。而且事先需要進行編譯。接下來腳本之家小編給大家揭曉js與java區(qū)別,感興趣的朋友一起看看吧2016-09-09

