If I have an array list of Courses, each with a name and array of students, what is an easy way of merging all the courses with the same name so that one course name only appears once with an array of all the students?
So that something like this:
ArrayList<Course> courses = {Course("math", {student1, student2}),
Course("art", {student3, student4}),
Course("math", {student5, student6})};
Would turn into this:
ArrayList<Course> courses = {Course("math", {student1, student2, student5, student6}),
Course("art", {student3, student4})};
EDIT: Here are the course and student classes, but I don't think they should be too important, I just want to be able to add the arrays of students together.
public class Course {
String name;
String[] students;
public Course(String name, String[] students) {
this.name = name;
this.students = students;
}
}
public class Student {
String name;
public Student(String name) {
this.name = name;
}
}
CodePudding user response:
Here are the steps:
Create HashMap <String, List> courseNameToStudents
Iterate over input courses elements. For each course element:
2a. Add (courseName, new List()) to courseNameToStudents if there is no courseName key (eg. 'math')
2b. Get value (list of students) from courseNameToStudents based on courseName key. Add all students from course to this list
Create result Course list. Go through entry set of courseNameToStudents. Create new courses using key of entry as courseName and value of entry as students. Add each course created this way to result list. Result list should be what you expect
Best of luck!
CodePudding user response:
You could collect the courses into a Map<String, List<String>>
then for each entry, recreate the Course
object:
Map<String, List<String>> map = new HashMap<>();
for (Course course : courses) {
var list = map.computeIfAbsent(course.name, k -> new ArrayList<String>());
list.addAll(Arrays.asList(course.students));
}
List<Course> coursesCombined = new ArrayList<>();
for (var entry : map.entrySet()) {
coursesCombined.add(
new Course(
entry.getKey(),
entry.getValue().toArray(new String[0])
)
);
}