1. 程式人生 > >Collections.sort()方法和lambda表示式結合實現集合的排序

Collections.sort()方法和lambda表示式結合實現集合的排序

1.使用Collections.sort()實現集合的排序,這裡的方法具體指的是:

  Collections.sort(List list, Compatator c)  

    第一個引數:為要進行排序的集合。

    第二個引數:Compatator的實現,指定排序的方式。

 

2.使用上面的方法進行排序,首先定義要排序的集合:

public class Student {private String name;
    private int score;public String getName() {
        return name;
    }

    
public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } }
    Student s1 = new Student(16, "aa", 44);
    Student s2 = new Student(18, "bb", 88);
    Student s3 
= new Student(17, "cc", 99); Student s4 = new Student(19, "dd", 66); List<Student> students = Arrays.asList(s1, s2, s3, s4);

3.結合lambda表示式對上面的students集合,按學生分數進行排序:

Collections.sort(students,
                (first, second) -> first.getScore() - second.getScore());  

 注意:由於Compatator介面只有一個抽象方法,因此可以使用lambda表示式