List<Student> students = new ArrayList<>();
students.add(new Student(1,"张三",11));
students.add(new Student(2,"李四",11));
students.add(new Student(3,"王五",13));
students.add(new Student(4,"赵六",14));
int studentId = 1;
Student student = students.stream().filter(o -> o.getId() == studentId).findAny().orElse(null);
如上,获取id为1的元素对象,如果不存在返回null。
获取11岁年纪的学生,如下:
int ageNum = 11;
List<Student> stuList = students.stream().filter(o -> o.getAge() == ageNum ).collect(Collectors.toList());
获取学生姓名集合,如下:
List<String> names = students.stream().map(Student::getName()).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
student类:
public class Student {
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age= age;
}
get...
set...
}