Get List item with lambdas

0

I am trying to migrate a code to Java 8, related to the classic exercises of Student / Teacher / Subject . I have some doubts about whether I am performing this lambda correctly to select a Student by id (Long field) of a List.

Code to obtain

return Student.getStudents().stream()
    .filter(student -> id.equals(student.getID()))
    .collect(Collectors.toList())
    .get(0);

The other doubt is, on the other hand, I try to make an insertion in a List always checking that the id field does not exist in the list of students, iterative I solve it, but I do not fit yet to see it with lambdas.

    
asked by dddenis 19.05.2016 в 23:49
source

1 answer

2

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;
}
    
answered by 20.05.2016 / 07:41
source