集合對(duì)像定義
集合對(duì)象以學(xué)生類(lèi)(StudentInfo)為例伦泥,有學(xué)生的基本信息,包括:姓名锦溪,性別不脯,年齡,身高刻诊,生日幾項(xiàng)防楷。
使用stream().sorted()進(jìn)行排序,需要該類(lèi)實(shí)現(xiàn)?Comparable?接口则涯,該接口只有一個(gè)方法需要實(shí)現(xiàn)复局,如下:
publicintcompareTo(T o);
有關(guān)compareTo方法的實(shí)現(xiàn)說(shuō)明,請(qǐng)參考:Java 關(guān)于重寫(xiě)compareTo方法
我的學(xué)生類(lèi)代碼如下:
?StudentInfo對(duì)象類(lèi)
添加測(cè)試數(shù)據(jù)
下面來(lái)添加一些測(cè)試用的數(shù)據(jù)粟判,代碼如下:
//測(cè)試數(shù)據(jù)亿昏,請(qǐng)不要糾結(jié)數(shù)據(jù)的嚴(yán)謹(jǐn)性List studentList =newArrayList<>();
studentList.add(newStudentInfo("李小明",true,18,1.76,LocalDate.of(2001,3,23)));
studentList.add(newStudentInfo("張小麗",false,18,1.61,LocalDate.of(2001,6,3)));
studentList.add(newStudentInfo("王大朋",true,19,1.82,LocalDate.of(2000,3,11)));
studentList.add(newStudentInfo("陳小跑",false,17,1.67,LocalDate.of(2002,10,18)));
?排序
使用年齡進(jìn)行升序排序
//排序前輸出StudentInfo.printStudents(studentList);//按年齡排序(Integer類(lèi)型)List studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge)).collect(Collectors.toList());//排序后輸出StudentInfo.printStudents(studentsSortName);
結(jié)果如下圖:
?使用年齡進(jìn)行降序排序(使用reversed()方法)
//排序前輸出StudentInfo.printStudents(studentList);//按年齡排序(Integer類(lèi)型)List studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge).reversed()).collect(Collectors.toList());//排序后輸出StudentInfo.printStudents(studentsSortName);
結(jié)果如下圖:
?使用年齡進(jìn)行降序排序,年齡相同再使用身高升序排序
//排序前輸出? ? ? ? StudentInfo.printStudents(studentList);
? ? ? ? //按年齡排序(Integer類(lèi)型)List studentsSortName = studentList.stream()
? ? ? ? ? ? ? ? .sorted(Comparator.comparing(StudentInfo::getAge).reversed().thenComparing(StudentInfo::getHeight))
? ? ? ? ? ? ? ? .collect(Collectors.toList());
? ? ? ? //排序后輸出StudentInfo.printStudents(studentsSortName);
結(jié)果如下圖: