I am trying to use the stream API to convert my flat object list to a hierarchy. I tried to search for similar questions here, but I didn't find one that would work for more than one level as in my case I need it to work for 2 levels.
My flat object entity object looks like this and I get a list of these objects from database
public class AdmNodeRelation {
private Integer id;
private AdmEntityNode admEntityNode;
private AdmRelation onward;
private AdmRelation outward;
}
I am trying to convert the above list of AdmNodeRelation objects to list of AdmNode so that each node will have its list of onward relation and which in turn will have a corresponding list of outward relation for the node:
public class AdmNode {
private Integer nodeId;
private String nodeName;
private List<AdmInwardRelation> inwardRelation = new ArrayList<>();
}
public class AdmInwardRelation {
private Integer relationId;
private String relationName;
private List<AdmOutwardRelation> outwardRelation = new ArrayList<>();
}
public class AdmOutwardRelation {
private Integer relationId;
private String relationName;
}
What I have tried:
I was able to get the desired result with forEach() and iterating through each of the flat object and creating the hirearchy structure but felt like there must be an easier way through the Stream API
<pre>Map<String, AdmNode> nodeMap = new HashMap();
for (AdmNodeRelation nodeRelation : nodeRelations) {
AdmEntityNode node = nodeRelation.getAdmEntityNode();
AdmNode modelNode = new AdmNode();
if (!nodeMap.containsKey(node.getNodeName())) {
BeanUtils.copyProperties(node, modelNode);
nodeMap.put(node.getNodeName(), modelNode);
} else {
modelNode = nodeMap.get(node.getNodeName());
}
AdmInwardRelation inwardRelation = new AdmInwardRelation();
BeanUtils.copyProperties(nodeRelation.getInwardRelation(), inwardRelation);
AdmOutwardRelation outwardRelation = new AdmOutwardRelation();
BeanUtils.copyProperties(nodeRelation.getOutwardRelation(), outwardRelation);
Optional<AdmInwardRelation> existingInwardRelation = modelNode.getInwardRelation()
.stream()
.filter(i -> i.getRelationName().equals(inwardRelation.getRelationName()))
.findAny();
if (existingInwardRelation.isEmpty()) {
inwardRelation.getOutwardRelation().add(outwardRelation);
modelNode.getInwardRelation().add(inwardRelation);
} else {
existingInwardRelation.get().getOutwardRelation().add(outwardRelation);
}
}
List<AdmNode> nodeListToUI = new ArrayList<>(nodeMap.values());