private static <T, R> void copyRecurse(TreeNode<R> copiedRoot, TreeDef<T> treeDef, T root, List<T> children, Function<? super T, ? extends R> mapper) { for (T child : children) { R mapped = mapper.apply(child); List<T> grandChildren = treeDef.childrenOf(child); copyRecurse(new TreeNode<>(copiedRoot, mapped, grandChildren.size()), treeDef, child, grandChildren, mapper); } }
/** * Creates a hierarchy of TreeNodes that copies the structure and content of the given tree, * using {@code mapper} to calculate the content of the nodes. */ public static <T, R> TreeNode<R> copy(TreeDef<T> treeDef, T root, Function<? super T, ? extends R> mapper) { // Leaves need to know their parent, but TreeQuery.copyLeavesIn makes that impossible // Parents need to know how many children they're goign to have, but TreeQuery.copyRootOut makes that impossible // thus, we do our own thing here List<T> children = treeDef.childrenOf(root); R mapped = mapper.apply(root); TreeNode<R> copyRoot = new TreeNode<>(null, mapped, children.size()); copyRecurse(copyRoot, treeDef, root, children, mapper); return copyRoot; }
assert(0 == TreeNode.leadingSpaces(test.get(0))); TreeNode<String> rootNode = new TreeNode<>(null, test.get(0)); TreeNode<String> lastNode = rootNode; int lastSpaces = 0; if (newSpaces == lastSpaces + 1) { lastNode = new TreeNode<>(lastNode, name); lastSpaces = newSpaces; } else if (newSpaces <= lastSpaces) { properParent = properParent.getParent(); lastNode = new TreeNode<>(properParent, name); lastSpaces = newSpaces; } else {