My basic class is:
public class Student {
public String name;
public String className; // In real code I'd have a second object for return to the end user
public List<String> classes; // Can be zero
}
I'd like to flatten it out so I can return something like
[
{
"name":"joe",
"class":"science"
},
{
"name":"joe",
"class":"math"
},
]
Obviously a stupid example for the sake of simplicity.
The only way I've been able to do it is through some long winded code like:
List<Student> students = getStudents();
List<Student> outputStudents = new ArrayList<>();
students.forEach(student -> {
if(student.getClasses().size() > 0) {
student.getClasses().forEach(clazz -> {
outputStudents.add(new Student(student.getName(), clazz));
});
} else {
outputStudents.add(student);
}
});
Looking if there is a way to simplify this, maybe using flapMap?