Необязательно в качестве типа возврата - PullRequest
2 голосов
/ 06 марта 2020

У меня проблемы с реализацией данного интерфейса, и я не совсем понимаю второй метод.

/**
 * 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);

Это то, что я сделал до сих пор

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();
    }

Дополнительный тип возврата ставит меня в затруднение. Я был бы очень признателен, если бы кто-нибудь дал ma реализацию для findById и методы save!

Ответы [ 2 ]

2 голосов
/ 06 марта 2020

Здесь вам не нужно found, просто верните студента, когда найдете его

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

Или, если вам нравится лямбда:

public Optional<Student> findById(int id) {
    return studentsList.stream()
        .filter(s -> s.getId() == id)
        .findFirst();
}
1 голос
/ 06 марта 2020

Поскольку вы уже используете Java -8, вы также можете использовать Stream s в реализации, например:

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