java - 按列表字段过滤对象列表

标签 java lambda collections java-8 java-stream

学生和类(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/

相关文章:

java - 尝试添加到数组但不起作用 - Java

java - Karaf 的 JPA [2.1] 功能/ bundle 列表

Python 记录集中的多线程

java - 为什么我的多线程任务无法正常工作?

java - 准备语句参数问题

java - Hibernate查询、QueryException异常

C# 计算列表中的出现次数

Java 8 lambda表达式多次更改Collection

java - 如何确定集合是否包含多个最大结果?

java - 实现 CharSequence 以便使用 String.join?