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

canpan14 :

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?

jwismar :

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());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=81599&siteId=1