java8stream操作:从集合中获取符合条件的元素

    List students = new ArrayList<>();

        students.add(new Student(1,"张三",90));
        students.add(new Student(2,"李四",60));
        students.add(new Student(3,"王五",30));
        students.add(new Student(4,"赵六",85));

        int studentId = 3;
        Student student = students.stream().filter(o -> o.getId() == studentId).findAny().orElse(null);

如上,获取id为3的元素对象,如果不存在返回null。

student类:

public class Student {

    private int id;
    private String name;
    private int score;

    public Student(int id, String name, int score) {
        this.id = id;
        this.name = name;
        this.score = score;
    }
get...
set...
}

你可能感兴趣的:(代码库)