java中如何實現(xiàn)對類的對象進行排序
我們需要對類按照類中的某一個屬性(或者多個屬性)來對類的對象進行排序,有兩種方法可以實現(xiàn),一種方法是類實現(xiàn)Comparable<T>接口,然后調(diào)用Collections.sort(List)方法進行排序,另一種方法是類不實現(xiàn)Comparable<T>接口,而在排序時使用Collections.sort(List, Comparator<T>)方法,并實現(xiàn)其中的Comparator<T>接口。
先創(chuàng)建一個簡單的學(xué)生類:
public class Student { private String name; private int age; public Student() {} public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
1、通過類實現(xiàn)Comparable<T>接口進行排序
public class Student implements Comparable<Student>{ private String name; private int age; public Student() {} public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } /** * 將對象按姓名字典序升序排序 * @param o * @return */ @Override public int compareTo(Student o) { return this.name.compareTo(o.getName()); } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
2、通過在Collections.sort()方法中實現(xiàn)Comparable<T>接口來實現(xiàn)排序
public class Client { public static void main(String[] args){ List<Student> students = new ArrayList<>(); students.add(new Student("a", 18)); students.add(new Student("c", 19)); students.add(new Student("b", 20)); Collections.sort(students, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.getAge()>o2.getAge()? -1:(o1.getAge()==o2.getAge()? 0:1); } }); for(Student student:students){ System.out.println(student.toString()); } } }
以上就是java中實現(xiàn)對類的對象進行排序的詳細內(nèi)容,感謝大家對腳本之家的支持。
相關(guān)文章
詳解springboot和vue前后端分離開發(fā)跨域登陸問題
這篇文章主要介紹了詳解springboot和vue前后端分離開發(fā)跨域登陸問題,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09一個JAVA小項目--Web應(yīng)用自動生成Word
前段時間接到一個Web應(yīng)用自動生成Word的需求,現(xiàn)整理了下一些關(guān)鍵步驟拿來分享一下。2014-05-05Mybatis-Plus實現(xiàn)用戶ID自增出現(xiàn)的問題解決
項目基于 SpringBoot + MybatisPlus 3.5.2 使用數(shù)據(jù)庫自增ID時, 出現(xiàn)重復(fù)鍵的問題,本文就來介紹一下解決方法,感興趣的可以了解一下2023-09-09