From List to Immutable Hierarchy-Tree (with Scala)

<p>As part of my job at&nbsp;<a href="https://www.hibob.com/" rel="noopener ugc nofollow" target="_blank">Hibob</a>, I&rsquo;ve been looking for a way to construct an Organizational-Chart out of a list of employees. This article shows one approach to creating an&nbsp;<em>immutable</em>&nbsp;tree structure out of a list of hierarchical objects.</p> <p><img alt="" src="https://miro.medium.com/v2/resize:fit:700/1*HMC1nJm4c83WbCIAutCt2A.png" style="height:316px; width:700px" /></p> <p>Org-Chart / bob</p> <p>Our input is a list of employees &mdash; each employee entry has an &ldquo;id&rdquo; and &ldquo;managerId&rdquo; property. The managerId can be empty or reference another employee on the list as its manager.</p> <p><img alt="" src="https://miro.medium.com/v2/resize:fit:700/1*QnWjlnGtp_RemNd1MdQ7Zg.png" style="height:329px; width:700px" /></p> <p>List &rArr; Tree</p> <p>I googled my way as a good lazy citizen does and found some&nbsp;<a href="https://stackoverflow.com/questions/444296/how-to-efficiently-build-a-tree-from-a-flat-structure" rel="noopener ugc nofollow" target="_blank">efficient ways to do the job</a>.</p> <p>Basically, all the solutions I&rsquo;ve found involve creating a &ldquo;Node&rdquo; object with an empty children array &mdash; then adding children to it on the fly pointing to other nodes. Adding children to a node object means we mutate this object after creation and therefore construct a tree made of mutable objects. This isn&rsquo;t necessarily bad and depends on one&rsquo;s needs, but I wanted to explore a way to construct nodes in an&nbsp;<a href="https://en.wikipedia.org/wiki/Immutable_object" rel="noopener ugc nofollow" target="_blank">Immutable</a>&nbsp;way without sacrificing much efficiency compared to mutable solutions.</p> <p><a href="https://medium.com/hibob-engineering/from-list-to-immutable-hierarchy-tree-with-scala-c9e16a63cb89"><strong>Visit Now</strong></a></p>