设置如下:我有一组课堂对象{MATH | SCIENCE | ENGLISH}
。我还有一个以Period
为键的地图和一组studentIds
作为值。这是从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
的{{1}}按教室顺序Period B
排序。然后,我按照课堂顺序"MATH, ENGLISH, SCIENCE"
排序studentIds
Period A
。所以对于前:
"MATH, ENGLISH, SCIENCE"
我当然可以创建任何帮助方法和结构来包含信息但我无法更改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 ...
方法并且必须使用它。任何人都可以指导我如何构建这个玩具问题解决方案吗?
答案 0 :(得分:1)
我认为这是一个有趣的问题。不知道为什么还没有回答。假设您有一个类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]