[英]Java Stream - throw exception in filter and return a list
I have created a Java stream:我创建了一个 Java stream:
List<Student> getStudentWithSameGrade(List<Student> students, Grade grade) {
return students.stream().filter(s -> s.getGradeId().equals(grade.getGid())).collect(Collectors.toList());
}
The above code returns a List<Student>
that satisfies the filter
check but I want to throw an exception for a student/list of students that don't satisfy this check.上面的代码返回一个满足
filter
检查的List<Student>
但我想为不满足此检查的学生/学生列表抛出异常。 I tried doing something like this,我试着做这样的事情,
return students.stream().filter(s -> s.getGradeId().equals(grade.getGid())).findAny()
.orElseThrow(() -> new EntityNotFoundException(ENTITY_NOT_FOUND));
However, the above code snippet returns a single student object instead of a list.但是,上面的代码片段返回一个学生 object 而不是一个列表。 I am relatively new to the
Stream
concept so would really appreciate some help on this.我对
Stream
概念相对较新,因此非常感谢您对此的帮助。
The easiest way would be simply to check:最简单的方法是简单地检查:
List<Student> getStudentWithSameGrade(List<Student> students, Grade grade) {
List<Student> students = students.stream().filter(s -> s.getGradeId().equals(grade.getGid())).collect(Collectors.toList());
if (students.isEmpty()) throw new EntityNotFoundException(ENTITY_NOT_FOUND);
else return students;
}
If you really need to stick to stream api, you could define your own collector:如果你真的需要坚持 stream api,你可以定义自己的收集器:
public static <T> Collector<T, ?, T> toNonEmptyList() {
return Collectors.collectingAndThen(
Collectors.toList(),
list -> {
if (list.isEmpty()) {
throw new IllegalStateException();
}
return list;
}
);
}
And then:接着:
return students.stream()
.filter(s -> s.getGradeId().equals(grade.getGid()))
.collect(toNonEmptyList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.