You do not need to collect the results in a list, this will filter all the elements when you can stop the navigation of Stream
with the first result found. You can change your lambda like this:
//student debería ir en minúscula
//si Student#getStudents es un método estático, te recomiendo
//cambiar el diseño
Optional<Student> optStudent = student.getStudents().stream()
.filter(s -> id.equals(s.getID()))
.findFirst(); //al encontrar el primero, se detiene la iteración del stream y devuelve un Optional
//evaluamos si el optional posee datos
//si no posee datos, entonces devolvemos null (lo clásico)
//la idea de usar Optional es no devolver null y evitar
//el clásico (if var == null)
//considera que Optional#get lanza una excepción en caso que
//no se haya encontrado un resultado
return optStudent.isPresent() ? optStudent.get() : null;
To enter an element in a list you do not need lambdas or iterations, what you need is to find if the element exists. To do this, you can use the code previously shown, like this:
public Optional<Student> findStudent(Integer id) {
return studentList.stream()
.filter(s -> id.equals(s.getID()))
.findFirst();
}
public boolean insert(Student student) {
boolean result = false;
Optional<Student> optStudent = findStudent(student.getId());
if (!optStudent.isPresent()) {
studentList.add(student);
result = true;
}
return result;
}