java - Java - 使用流获取具有特定属性的列表元素
问题描述
我有两个名为School
and的类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());
如何使用流来获取将给定学生作为首选的学校?
解决方案
这应该完成您指定的内容:
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());
推荐阅读
- github - 致命:解析“conf/gitolite.conf-compiled.pm”失败:没有这样的文件或目录
- netlogo - 西北扩展和代理导航
- python-3.x - 如果数据框中存在列 x1,如何给出标志 2,如果数据框中存在列 x2,如何给出标志 2.5
- android - HeaderScrollingViewBehavior 导致崩溃的原因是什么?
- salesforce - Salesforce 使用 url hacking 创建具有记录类型选择的视图
- android - Admob 广告未在 Android 上显示,但在 iOS 上有效——Flutter
- r - 如何绘制具有不同分类变量的大量密度图
- ios - 如何在滚动视图上添加多个视图控制器而不重叠
- encryption-symmetric - 如何减少对称加密中使用的密钥数
- regex - 验证 AWS 访问密钥和密钥