学生和类(class)有两个普通对象,如下所示:
public class Student {
List<Course> courses;
...
}
public class Course {
String name;
...
}
如果我们有学生
的列表
,我们如何根据类(class)名称过滤一些学生?
- 首先我尝试
flatMap
来回答这个问题,但它返回了类(class) 对象而不是学生对象。 - 然后我使用
allMatch
(以下代码)。 然而它返回学生列表,但List
始终为空。是什么 有问题吗?
List<Student> studentList;
List<Student> AlgorithmsCourserStudentList = studentList.stream().
filter(a -> a.stream().allMatch(c -> c.getCourseName.equal("Algorithms"))).
collect(Collectors.toList());
最佳答案
您需要anyMatch
:
List<Student> studentList;
List<Student> algorithmsCourseStudentList =
studentList.stream()
.filter(a -> a.getCourses()
.stream()
.anyMatch(c -> c.getCourseName().equals("Algorithms")))
.collect(Collectors.toList());
allMatch
只会向您提供学生
,他们的所有类(class)
都被命名为“算法”
.anyMatch
将为您提供所有至少拥有一门名为“算法”
类(class)
的学生
>.
关于java - 按列表字段过滤对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46631960/