Last active
August 17, 2016 13:50
-
-
Save crocker/27326a01810bb9646e7779ff2e21a71c to your computer and use it in GitHub Desktop.
Scala multi-root tree or forest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.signalpath.model | |
import scala.collection.mutable | |
class Forest[A]()(ordering: Ordering[A]) { | |
val tree = new mutable.LinkedHashMap[Option[A], mutable.ListBuffer[A]]() | |
def addNode(parent: Option[A], node: A): Unit = { | |
val children = tree.get(parent).map(_ += node).getOrElse(mutable.ListBuffer[A](node)) | |
tree.put(parent,children.sorted(ordering)) | |
} | |
def getChildren(parent: Option[A]): List[A] = { | |
tree.getOrElse(parent, List.empty[A]).toList | |
} | |
def getRootNodes(): Set[Option[A]] = { | |
tree.keySet.toSet | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment