首页 > 解决方案 > Java - 使用流获取具有特定属性的列表元素

问题描述

我有两个名为Schooland的类Student,一组学校,一个学生列表和两张地图,其中包含学校在学生方面的偏好,反之亦然:

Set<School> schoolSet = new TreeSet<>();
Collections.addAll(schoolSet, schools);

List<Student> studentList = new LinkedList<>(Arrays.asList(students));

Map<School, List<Student>> schoolPrefMap = new TreeMap<>();
Map<Student, List<School>> stdPrefMap = new HashMap<>();

我正在使用不同的实现,因为这是我必须完成的任务之一。

我正在尝试使用 java 流创建一个查询,该流从集合中返回以某个学生为最高优先级的学校,因此该学生的索引在该特定学校键的值列表中应该为 0。

我有一个尝试类似的例子,只让他的偏好中至少有特定学校的学生

List<School> target = Arrays.asList(schools[0], schools[2]);

List<Student> result = studentList.stream()
        .filter(std -> stdPrefMap.get(std).containsAll(target))
        .collect(Collectors.toList());

如何使用流来获取将给定学生作为首选的学校?

标签: javajava-stream

解决方案


这应该完成您指定的内容:

Student target = ...
schoolSet.stream()
        .filter(school -> {
            List<Student> preferredStudents = schoolPrefMap.get(school);
            return !preferredStudents.isEmpty() && preferredStudents.get(0).equals(target);
        }).collect(Collectors.toList());

请问您为什么不使用 Map<School, PriorityQueue<Student>> 和 Map<Student, PriorityQueue<School>> (因为它非常适合具有额定偏好并使用 contains() / containsAll 的情况() 就一个列表是不是很高效)?

在这种情况下,您的代码将如下所示:

schoolSet.stream()
        .filter(school -> {
            Queue<Student> preferredStudents = schoolPrefMap.get(school);
            return !preferredStudents.isEmpty() && preferredStudents.peek().equals(target);
        }).collect(Collectors.toList());

推荐阅读