gpt4 book ai didi

java-8 - Java 8 流收集集

转载 作者:行者123 更新时间:2023-12-04 20:30:58 24 4
gpt4 key购买 nike

我有两张 map ,即

Map<String, Set<String>> courseTeacherMap = {course1: [teacher1, teacher2], ...}
Map<String, Set<String>> teacherStudentMap = {teacher1: [student1, student2], ...}

我定义了一个类 courseStudentPair它有一个非常简单的结构
public class courseStudentPair{
String studentName; // Taken from teacherStudentMap
String courseName; // Taken from courseTeacherMap
}

我的目标是获得一个 Set<courseStudentPair>在两张 map 中。只要老师 A 正在教授类(class) C,在 teacherStudentMap 中键 A 的值集中的每个学生被认为是选择 C ​​的学生。

例如,给定
Map<String, Set<String>> courseTeacherMap = {c1: [t1], c2:[t2], c3:[t1, t2]}
Map<String, Set<String>> teacherStudentMap = {t1: [s1], t2:[s1, s2]}

结果应该是 *(student, course) 表示下面示例中的 courseStudentPair 对象*
Set<courseStudentPair> result = [(c1, s1), (c2, s1), (c2, s2), (c3, s1), (c3, s2)]

使用 for 循环很简单,但我正在学习 Java 8 中的流函数,这对我来说似乎很复杂。您可以假设 courseStudentPair类定义了构造函数或构建器。

最佳答案

本着同样的精神,您可以生成(类(class),老师)的每个组合,然后查找与该老师关联的学生。这可能会生成重复项(例如 (c3, s1)),因此请确保您的 CourseStudentPair类实现 equals()hashCode()基于这两个领域。

import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;

...

Set<CourseStudentPair> result =
courseTeacherMap.entrySet()
.stream()
.flatMap(e -> e.getValue()
.stream()
.flatMap(t -> teacherStudentMap.getOrDefault(t, emptySet()).stream().map(s -> new CourseStudentPair(e.getKey(), s))))
.collect(toSet());
/*
Output:

CourseStudentPair{studentName='c1', courseName='s1'}
CourseStudentPair{studentName='c2', courseName='s2'}
CourseStudentPair{studentName='c2', courseName='s1'}
CourseStudentPair{studentName='c3', courseName='s2'}
CourseStudentPair{studentName='c3', courseName='s1'}
*/

关于java-8 - Java 8 流收集集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46558481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com