设置如下:我有一组教室对象{MATH | SCIENCE | ENGLISH}
。我还有一个以Period
为键的map和一组studentIds
为值的map。这是从getPeriodStudentMappingForClassroom()
方法返回的现在,作为输入,我得到了字符串"MATH, ENGLISH, SCIENCE"
,它指示返回studentIds
的顺序(选项的数量是固定的)我还有另一个字符串,它有任意数量的句点,例如"B, A"
(可以有任意数量的句点)。下面是一个可视化示例:
Classroom MATH:
Period A -> Set<Integer> studentIds
Period B -> Set<Integer> studentIds
Classroom ENGLISH:
Period A -> Set<Integer> studentIds
Period B -> Set<Integer> studentIds
作为输出,我希望返回的
studentIds
按教室和时段排序,这样首先我得到studentIds
的所有Period B
。studentIds
的这些Period B
按教室顺序排序。然后我得到"MATH, ENGLISH, SCIENCE"
的studentIds
按教室顺序排序。所以对于前男友来说:Input:
String classroomOrder = "MATH, ENGLISH, SCIENCE"
String periodOrder = "B, A"
public Map<String, <Set<Integer>> getPeriodStudentMappingForClassroom(String classroom)
Output:
Set<Integer> studentIds
Ex.
Period A studentIds in Math classroom
Period A studentIds in English classroom
Period A studentIds in Science classroom
Period B studentIds in Math classroom ...
当然,我可以创建任何helper方法和结构来包含信息,但是我不能更改
Period A
方法,必须使用它有人能指导我如何构造这个玩具问题的解决方案吗? 最佳答案
我认为这是个有趣的问题。不知道为什么还没有答案假设您有一个类ClassRoom
,它将句点、课程名称和学生id封装如下
public static class ClassRoom {
private String period; // A or B
private String courseName; // MATH, SCIENCE or ENGLISH
private Set<Integer> studentIds;
public ClassRoom(String period, String courseName, Integer... studentIds) {
this.period = period;
this.courseName = courseName;
this.studentIds = new HashSet<>(Arrays.asList(studentIds));
}
public String getPeriod() {
return period;
}
public String getCourseName() {
return courseName;
}
public Set<Integer> getStudentIds() {
return studentIds;
}
@Override
public String toString() {
return "Period='" + period + '\'' +
", CourseName='" + courseName + '\'' +
", studentIds=" + studentIds;
}
}
然后可以按如下方式打印分类列表
List<String> order = Arrays.asList("MATH", "ENGLISH", "SCIENCE");
classes.stream().sorted(
comparing(ClassRoom::getPeriod)
.thenComparingInt(c -> order.indexOf(c.getCourseName())))
.forEach(System.out::println);
输出
Period='A', CourseName='MATH', studentIds=[3, 4, 89, 90, 78]
Period='A', CourseName='MATH', studentIds=[34, 3, 4, 5, 6]
Period='A', CourseName='MATH', studentIds=[2, 3, 4, 5, 232]
Period='A', CourseName='SCIENCE', studentIds=[1, 2, 3, 4, 57]
Period='A', CourseName='SCIENCE', studentIds=[34, 2, 3, 5]
Period='B', CourseName='ENGLISH', studentIds=[2, 5, 7]
Period='B', CourseName='ENGLISH', studentIds=[1, 2, 34, 3, 12]