[1,2,[3,4,[5]],6,[[7,8]]]
[1,2,3,4,5,6,7,8]
package zzz.nestedlist;
import static zzz.nestedlist.Node.node;
public class NestedList {
public static void main(String[] args) {
Node root = node(
node(1),
node(2),
node(
node(3),
node(4),
node(
node(5))),
node(6),
node(
node(
node(7),
node(8))));
print(root);
print(
root.flat());
}
private static void print(Node root) {
System.out.println(root.toString());
}
}
package zzz.nestedlist;
import static java.util.Arrays.asList;
import java.util.ArrayList;
import java.util.List;
public class Node {
boolean isLeaf;
int val;
List<Node> children;
public static Node node(int val) {
return leaf(val);
}
public static Node node(Node... nodes) {
return branch(asList(nodes));
}
private static Node leaf(int val) {
Node node = new Node();
node.isLeaf = true;
node.val = val;
return node;
}
private static Node branch(List<Node> nodes) {
Node node = new Node();
node.isLeaf = false;
node.children = nodes;
return node;
}
public Node flat() {
if (isLeaf)
return node(leaf(val));
List<Node> nodes = new ArrayList<>();
for (Node n : children)
nodes.addAll(n.flat().children);
return branch(nodes);
}
@Override
public String toString() {
if (isLeaf)
return val + "";
String body = children.stream()
.map(Object::toString)
.reduce("", (a, b) -> a + "," + b);
return "[" + body.substring(1) + "]";
}
}