public class Node {
final Map<String, Node> valueMap = new HashMap<>();
}
public Stream<Node> stream(Order order) {
//valueMap is children
Stream<Node> childrenStream = this.valueMap.values().stream().map(i -> i.stream(order)).reduce(Stream::concat).orElse(Stream.empty());
//this is parent
switch (order) {
case PRE:
return Stream.concat(Collections.singleton(this).stream(), childrenStream);
case SUFFIX:
return Stream.concat(childrenStream, Collections.singleton(this).stream());
default:
throw new UnsupportedOperationException();
}
}
因为children没有区分左右,是多个的情况,所以没有中缀遍历,可以自行根据情况实现
public Stream<Node> stream(Order order){
return stream((i)->true,order);
}
public Stream<Node> stream(Predicate<Node> predicate,Order order) {
//valueMap is children
Stream<Node> childrenStream = this.valueMap.values().stream().filter(predicate).map(i -> i.stream(predicate,order)).reduce(Stream::concat).orElse(Stream.empty());
//this is parent
if (predicate.test(this)){
switch (order) {
case PREFIX:
return Stream.concat(Collections.singleton(this).stream(), childrenStream);
case SUFFIX:
return Stream.concat(childrenStream, Collections.singleton(this).stream());
default:
throw new UnsupportedOperationException();
}
}else {
return childrenStream;
}
}
//过滤特定节点,以及后代