养生 装修 购物 美食 感冒 便秘 营销 加盟 小吃 火锅 管理 创业 搭配 减肥 培训 旅游

java实体类多属性排序

时间:2024-10-19 08:54:05

通过本文章学习,可以掌握java中对实体类的多个属性分别升序降序自由排序的知识点,并在最后附上代码

工具/原料

eclipse

方法/步骤

1、定义一个实体类Student,因为主要关注排序,所以实体类略显简单。

java实体类多属性排序

2、添加几条数据,为后续实验做准备

java实体类多属性排序

3、定义两个排序对象,先按chinese由低到高排序,chinese相同,则english由低到高排序。

java实体类多属性排序

java实体类多属性排序

4、按chinese由低咦筋庑檗到高排序,chinese相同,则英语由高到低排序。(即调用排序对象的reversed()方法)

java实体类多属性排序

java实体类多属性排序

5、按chinese由高到低排序,chinese相同,则english由高到低排序。

java实体类多属性排序

java实体类多属性排序

6、全部代码:impo筠续师诈rtjava.util.ArrayList;importjava.util.Collections;import惺绅寨瞀java.util.Comparator;importjava.util.List;classStudent{ //学号 privateStringsno; //语文分数 privatefloatchinese; //英语分数 privatefloatenglish; publicStudent(Stringsno,floatchinese,floatenglish){ super(); this.sno=sno; this.chinese=chinese; this.english=english; } publicStringgetSno(){ returnsno; } publicfloatgetChinese(){ returnchinese; } publicvoidsetChinese(floatchinese){ this.chinese=chinese; } publicfloatgetEnglish(){ returnenglish; } publicvoidsetEnglish(floatenglish){ this.english=english; }}publicclassMain{ publicstaticvoidmain(String[]args){ List<Student>students=newArrayList<Student>(); students.add(newStudent("01",63.0f,75f)); students.add(newStudent("02",65.0f,72f)); students.add(newStudent("03",63.0f,82f)); students.add(newStudent("04",72.0f,72f)); students.add(newStudent("05",63.0f,65f)); Comparator<Student>compareChinese= Comparator.comparing(Student::getChinese); Comparator<Student>compareEnglish= Comparator.comparing(Student::getEnglish); Collections.sort(students, compareChinese.thenComparing(compareEnglish)); for(Students:students){ System.out.println(s.getSno()+","+s.getChinese()+"," +s.getEnglish()); } System.out.println("---------------------------------------"); Collections.sort(students, compareChinese.thenComparing(compareEnglish.reversed())); for(Students:students){ System.out.println(s.getSno()+","+s.getChinese()+"," +s.getEnglish()); } System.out.println("---------------------------------------"); Collections.sort(students, compareChinese.reversed(). thenComparing(compareEnglish.reversed())); for(Students:students){ System.out.println(s.getSno()+","+s.getChinese()+"," +s.getEnglish()); } }}

© 一点知识