Java8 使用 stream().sorted()對List集合進行排序

集合對像定義

集合對象以學生類(StudentInfo)為例,有學生的基本信息,包括:姓名,性別,年齡,身高,生日幾項。

使用stream().sorted()進行排序,需要該類實現?Comparable?接口,該接口只有一個方法需要實現,如下:

publicintcompareTo(T o);

有關compareTo方法的實現說明,請參考:Java 關于重寫compareTo方法

我的學生類代碼如下:

?StudentInfo對象類

添加測試數據

下面來添加一些測試用的數據,代碼如下:

//測試數據,請不要糾結數據的嚴謹性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)));

?排序

使用年齡進行升序排序

//排序前輸出StudentInfo.printStudents(studentList);//按年齡排序(Integer類型)List studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge)).collect(Collectors.toList());//排序后輸出StudentInfo.printStudents(studentsSortName);

結果如下圖:

?使用年齡進行降序排序(使用reversed()方法)

//排序前輸出StudentInfo.printStudents(studentList);//按年齡排序(Integer類型)List studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge).reversed()).collect(Collectors.toList());//排序后輸出StudentInfo.printStudents(studentsSortName);

結果如下圖:

?使用年齡進行降序排序,年齡相同再使用身高升序排序

//排序前輸出? ? ? ? StudentInfo.printStudents(studentList);

? ? ? ? //按年齡排序(Integer類型)List studentsSortName = studentList.stream()

? ? ? ? ? ? ? ? .sorted(Comparator.comparing(StudentInfo::getAge).reversed().thenComparing(StudentInfo::getHeight))

? ? ? ? ? ? ? ? .collect(Collectors.toList());

? ? ? ? //排序后輸出StudentInfo.printStudents(studentsSortName);

結果如下圖:

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容