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表达式

猜你喜欢

转载自www.cnblogs.com/liuxuelin/p/10126929.html
今日推荐