Java List排序
需求:對學生對象按照其 分數(降序)進行排序,當分數相同時按學號(從小到大)排序
實現:利用Collections類的 sort(List<T> list,Comparator<? super T> c) 方法,自定義比較器對象對指定對象進行排序
代碼實現
Student類
class Student{ private int id; private String name; private float score; //成績 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getScore() { return score; } public void setScore(float score) { this.score = score; } }比較器類
//先按成績 降序 排序,如果成績一樣的話按id 升序 排序 class StudentComparator implements Comparator<Student>{ /** * return a negative integer, zero, or a positive integer as the first argument is less than, * equal to, or greater than the second. */ @Override public int compare(Student s1, Student s2) { if(s1.getScore()>s2.getScore()){ //greater return -1; }else if(s1.getScore()==s2.getScore()){ //equals if(s1.getId()>s2.getId()){ return 1; }else if(s1.getId()==s2.getId()){ return 0; }else{ return -1; } }else{ //less return 1; } } }Demo類
public class ListSortDemo { public static void main(String[] args) { Student s1 = new Student(); s1.setId(10001); s1.setName("cat"); s1.setScore(99.5f); Student s2 = new Student(); s2.setId(10008); s2.setName("bba"); s2.setScore(100.0f); Student s3 = new Student(); s3.setId(10011); s3.setName("bac"); s3.setScore(89.5f); List<Student> list = new ArrayList<Student>(); list.add(s1); list.add(s2); list.add(s3); System.out.println("排序之前-----------------------"); for(Student stu:list){ System.out.println("id="+stu.getId()+" name="+stu.getName()+" score="+stu.getScore()); } Collections.sort(list, new StudentComparator()); //排序 System.out.println("排序之后-----------------------"); for(Student stu:list){ System.out.println("id="+stu.getId()+" name="+stu.getName()+" score="+stu.getScore()); } } }
運行結果
排序之前-----------------------
id=10001 name=cat score=99.5
id=10008 name=bba score=100.0
id=10011 name=bac score=89.5
排序之后-----------------------
id=10008 name=bba score=100.0
id=10001 name=cat score=99.5
id=10011 name=bac score=89.5
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!