@Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (!(obj instanceof Tree)) return false; final Tree that = (Tree) obj; return !((this.isRoot() && !that.isRoot()) || (!this.isRoot() && that.isRoot())) && !(!this.isRoot() && !this.value.equals(that.value)) && this.children.equals(that.children); }
@Override public int hashCode() { return (this.isRoot() ? 0 : this.value.hashCode()) + this.children.hashCode(); }
@SuppressWarnings("unchecked") public <V> V reduce(final V accum, final BiFunction<V, T, V> s) { V ret = accum; try { if (!isRoot()) { ret = s.apply(ret, this.value); } for(Tree<T> child : this.children) { ret = child.reduce(ret, s); } } catch (ReduceComplete e) { ret = (V)e.result; } return ret; }
public List<List<T>> pathsToValue(final boolean includeValue, final Function<T, Boolean> pred) { final List<List<T>> paths = new ArrayList<>(); if (!isRoot() && pred.apply(this.value)) { List<T> path = new ArrayList<>(); if (includeValue) { path.add(this.value); } paths.add(path); } this.children().forEach(c -> { final List<List<T>> childPaths = c.pathsToValue(includeValue, pred); if (!childPaths.isEmpty() && !isRoot()) { childPaths.forEach(p -> p.add(0, this.value)); } paths.addAll(childPaths); }); return paths; }
public Set<SchemaElement> elementsForElement(final List<SchemaElement> path) { Tree<SchemaElement> tree = schemaTree(); final Deque<SchemaElement> pathStack = new ArrayDeque<>(path); while (tree != null && !pathStack.isEmpty()) { final SchemaElement cur = pathStack.pop(); tree = tree.children().stream() .filter(t -> t.value().qname().equals(cur.qname())) .findFirst() .orElse(null); } final Set<SchemaElement> ret = new HashSet<>(); if (tree != null && !tree.isRoot()) { ret.addAll(tree.children().stream() .map(Tree::value) .collect(Collectors.toList())); } return ret; }
public Set<String> attributesForElement(final List<SchemaElement> path) { Tree<SchemaElement> tree = schemaTree(); final Deque<SchemaElement> pathStack = new ArrayDeque<>(path); while (tree != null && !pathStack.isEmpty()) { final SchemaElement cur = pathStack.pop(); tree = tree.children().stream() .filter(t -> t.value().qname().equals(cur.qname())) .findFirst() .orElse(null); } final Set<String> ret = new HashSet<>(); if (tree != null && !tree.isRoot()) { ret.addAll(tree.value().attributes()); } return ret; }