Skip to content
Advertisement

Flat tree of objects while keeping father and child

I have a class Employee which has a tree structure with property team

JavaScript

Using Java lambdas I need to flat this tree into same level list while converting Employee class into the following ConvertedEmployee while storing names in dedicated lead and subordinates properties. So ConvertedEmployee is in some sense a node which keeps parent and children. And I need to have a list of those.

JavaScript

So final result should be List<ConvertedEmployee>

I was thinking to use recursion here.

But I can only flat the tree and can’t rebuild it’s parents.

EDIT: Input is instance of Employee object that basically has a tree inside team

Advertisement

Answer

A non-recursive solution using concatenation of the streams followed by filtering out the “duplicated” entries which do not have lead field set:

JavaScript

Test for the following setup:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement