2017-10-08 75 views
2

有对学生和课程两个滑动对象是这样的:由列表字段进行筛选对象的列表

public class Student { 
    List<Course> courses; 
    ... 
} 
public class Course { 
    String name; 
    ... 
} 

如果我们有Students一个list,我们怎样才能通过的名称进行筛选一些学生他们的课程?

  • 首先我尝试flatMap回答这个问题,但它返回当然 对象,而不是学生的对象。
  • 然后我使用allMatch(以下代码)。然而 返回学生名单,但始终List是空的。什么是 问题?
List<Student> studentList; 
List<Student> AlgorithmsCourserStudentList = studentList.stream(). 
    filter(a -> a.stream().allMatch(c -> c.getCourseName.equal("Algorithms"))). 
    collect(Collectors.toList()); 

回答

7

您需要anyMatch

List<Student> studentList; 
List<Student> algorithmsCourseStudentList = 
    studentList.stream() 
       .filter(a -> a.getCourses() 
          .stream() 
          .anyMatch(c -> c.getCourseName().equals("Algorithms"))) 
       .collect(Collectors.toList()); 
  • allMatch只会给你Student s表示他们所有的Course s的命名"Algorithms"

  • anyMatch会给你所有Student S作至少一个Course命名"Algorithms"

2

对于每个学生获得课程,并查找是否有任何匹配的课程名称的学生的课程。

Course.java:

public class Course { 
    private String name; 

    public String getName() { 
     return name; 
    } 
} 

Student.java:

import java.util.ArrayList; 
import java.util.List; 
import java.util.stream.Collectors; 

public class Student { 
    private List<Course> courses; 

    public List<Course> getCourses() { 
     return courses; 
    } 

    public static void main(String... args) { 
     List<Student> students = new ArrayList<>(); 

     List<Student> algorithmsStudents = students.stream() 
       .filter(s -> s.getCourses().stream().anyMatch(c -> c.getName().equals("Algorithms"))) 
       .collect(Collectors.toList()); 
    } 
} 

编辑:

List<Student> AlgorithmsCourserStudentList = studentList.stream(). 
    filter(a -> a.stream().allMatch(c -> c.getCourseName.equal("Algorithms"))). 
    collect(Collectors.toList()); 
  • 这里您的代码将无法编译,在过滤器'a'是一名学生,这是做的es没有stream()方法。
  • 不能使用flatMap()到课程的学生的名单转换为流,因为那时你不能收取学生进一步上
  • allMatch产量true如果列表中的所有元素相匹配的谓语,false如果有一个元素不匹配。因此,如果代码是正确的你会被测试,如果所有的学生的课程有名称为“算法”,但要测试是否有符合条件的单个元素。请注意,allMatchanyMatch不需要返回列表,它们会返回boolean,这就是您可以在过滤器中使用它们的原因。
+0

要发布一个答案一次10分钟的已经发布后,比以前的答案低质量的,因为你是比代码转储和他多一点提供解释。 –

+0

不,另一个答案在我回答这个问题时是不正确的。我在输入时编辑了它。 –

1

我同意@Eran。您也可以在filter使用method references如下:

students.stream() 
      .filter(s -> s.getCourses().stream() 
        .map(Course::getName) 
        .anyMatch("Algorithms"::equals) 
      ).collect(Collectors.toList());