Java - Turn Object with List Variable into a List of Objects

Viewed 384

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?

2 Answers

One way to do that could be to partition the current list of Students based on the conditions if the classes within them are empty or not

Map<Boolean, List<Student>> conditionalPartitioning = students.stream()
        .collect(Collectors.partitioningBy(student -> student.getClasses().isEmpty(), Collectors.toList()));

then further use this partitioning to flatMap to a list of new students given those have classes within them as and concatenate them with the other partition to finally collect into the result as :

List<Student> result = Stream.concat(
        conditionalPartitioning.get(Boolean.FALSE).stream() // classes as a list
                .flatMap(student -> student.getClasses() // flatmap based on each class
                        .stream().map(clazz -> new Student(student.getName(), clazz))),
        conditionalPartitioning.get(Boolean.TRUE).stream()) // with classes.size = 0
        .collect(Collectors.toList());

Yes, you should be able to do something like this:

Student student = ?
List<Student> output = 
    student
        .getClasses()
        .stream()
        .map(clazz -> new Student(student.getName, student.getClassName, clazz))
        .collect(Collectors.toList());

For a single student. For a collection of students it's a little more complicated:

(Updated due to observation in comment from @nullpointer. Thanks!)

List<Student> listOfStudents = getStudents();
List<Student> outputStudents =
    listOfStudents
        .stream()
        .flatMap(student -> {
            List<String> classes = student.getClasses();
            if (classes.isEmpty()) return ImmutableList.of(student).stream();
            return classes.stream().map(clazz -> new Student(student.getName(), student.getClassName(), ImmutableList.of(clazz)));
        })
        .collect(Collectors.toList());
Related