Flattening the user defined object A having list of objects B, so the structure will be List of object A having a single object of B

Viewed 31

I have an Object Parent having structure as below

public class Parent {
    private Long id;    
    private List<Child> children;
}

I want to flatten the Parent object so the structure will be like:

public class Parent {
    private Long id;    
    private Child children;
}

and the result would be List<Parent> which will accommodate all of the Children's as single object in Parent list.

1 Answers

You will need a class that contains Child object and then you can flatten the data in current Parent class with this:

List<Child> childrenList = parent.getChildren();
childrenList.stream().map(child->{new ParentWithChild(p.id, child)}).collect(Collectors.toList());

Where childrenList id the list of childrens in the parent object. And ParentWithChild will have the structure as:

public class ParentWithChild {
    private Long id;    
    private Child children;
}

You can obviously modify the existing class as:

class Parent {
public Parent(Long id, List<Child> children){
    this.id=id;
    this.children = children;
}

public Parent(Long id, Child child){
    this.id=id;
    this.child = child;
}
private Long id;
private List<Child> children;
private Child child;

}

But this will not really be a good approach.

Related