我在实现给定的接口时遇到了麻烦,我不太了解第二种方法。
/**
* 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的实现并保存方法,我将不胜感激!
[这里,您不需要found
只需找到学生就将其归还]
public Optional<Student> findById(int id) {
for (Student s : studentsList) {
if (s.getId() == id) {
return Optional.of(s);
}
}
return Optional.empty();
}
或者,如果您喜欢lambda:
public Optional<Student> findById(int id) {
return studentsList.stream()
.filter(s -> s.getId() == id)
.findFirst();
}
您的findById
方法几乎是正确的,如果ID匹配,您只需要返回包含Optional
的Student
。您将要使用Optional#of(T)
:
返回描述给定非空值的Optional。
并且您可以删除Optional#of(T)
局部变量,因为它是不必要的。
found
您似乎尚未尝试实现@Override
public Optional<Student> findById(int id) {
for (Student s : studentsList) {
if (s.getId() == id) {
return Optional.of(s); // first Student with matching ID found, return it
}
}
return Optional.empty(); // no Student with matching ID found
}
。由于这个问题就像是一项家庭作业,我倾向于不仅仅给出解决方案。话虽如此,您将希望利用save
来避免代码重复,这意味着您应该研究findById
和Optional#isPresent()
,或者,如果使用的是Java 9+,则应查看Optional#isPresent()
。
要了解有关Optional#get()
的更多信息,建议阅读其所有Javadoc:Optional#get()
由于您已经在使用Java-8,因此您也可以在实现中使用Optional#ifPresentOrElse(Consumer,Runnable)
,例如:
Optional#ifPresentOrElse(Consumer,Runnable)