Optional as a return type

Viewed 270

I'm having trouble implementing a given interface and I don't really understand the second method.

/**
 * Saves the given student. If the given student is already present in the
 * repository then the method will act as an update operation.
 *
 * @param student must not be {@literal null}
 * @return the saved student; will never be {@literal null}
 * @throws IllegalArgumentException in case the given {@literal student} is {@literal null}.
 */
Student save(Student student);

/**
 * Retrieves a student by its id.
 *
 * @param id the unique student identifier
 * @return the student with the given id or {@literal Optional#empty()} if none found.
 */
Optional<Student> findById(int id);

/**
 * Deletes the student with the given id.
 *
 * @param id id the unique student identifier
 */
public void deleteById(int id);

This is what I've done so far

public class StudentCrudRepositoryImplementation implements StudentCrudRepository {
    private List<Student> studentsList;

    public StudentCrudRepositoryImplementation() {
        studentsList = new ArrayList<>();
    }

    @Override
    public Student save(Student student) {
        if (student == null) {
            throw new IllegalArgumentException();
        }
       //check if the given student has the same id with an already existing one, if yes update it
    }

    @Override
    public Optional<Student> findById(int id) {
        boolean found = false;
        for (Student s : studentsList) {
            if (s.getId() == id) {
                found = true;
                return
            }
        }
        return Optional.empty();
    }

The Optional return type puts me in difficulty. I would really appreciate if someone gave ma an implementation for findById and save methods!

2 Answers

Here, you don't need found just return the student when you find it

public Optional<Student> findById(int id) {
    for (Student s : studentsList) {
        if (s.getId() == id) {
            return Optional.of(s);
        }
    }
    return Optional.empty();
}

Or if you like lambda:

public Optional<Student> findById(int id) {
    return studentsList.stream()
        .filter(s -> s.getId() == id)
        .findFirst();
}

Since you are already on Java-8, you can also make use of Streams in the implementation such as:

public Optional<Student> findById(int id) {
    return studentsList.stream()
            .filter(s -> s.getId() == id)
            .findAny(); // returns 'Optional<Student>'
}
Related