com.diffplug.common.base.TreeNode Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of durian Show documentation
Show all versions of durian Show documentation
Durian - Guava's spikier (unofficial) cousin
/**
* Copyright 2015 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.diffplug.common.base;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/** Allows Trees to be manually defined across any object. */
public final class TreeNode {
final TreeNode parent;
final T obj;
List> children = null;
public TreeNode(TreeNode parent, T obj) {
this.parent = parent;
this.obj = obj;
if (parent != null) {
if (parent.children == null) {
parent.children = new ArrayList<>();
}
parent.children.add(this);
}
}
public TreeNode getParent() {
return parent;
}
public T getObj() {
return obj;
}
public List> getChildren() {
return children == null ? Collections.emptyList() : children;
}
/** Creates a hierarchy of TreeNodes that copies the structure and content of the given Tree. */
public static TreeNode copy(T root, TreeDef treeDef) {
TreeNode copyRoot = new TreeNode<>(null, root);
copyRecurse(copyRoot, treeDef);
return copyRoot;
}
private static void copyRecurse(TreeNode root, TreeDef treeDef) {
List children = treeDef.childrenOf(root.obj);
for (T child : children) {
copyRecurse(new TreeNode<>(root, child), treeDef);
}
}
/** TreeDef for the generic TreeNode class. */
public static TreeDef.Parented> treeDef() {
return new TreeDef.Parented>() {
@Override
public List> childrenOf(TreeNode root) {
return root.getChildren();
}
@Override
public TreeNode parentOf(TreeNode child) {
return child.parent;
}
};
}
}