使⽤Java8流遍历递归数据结构
Streams API是Java 8中的真正瑰宝,我⼀直在为它们寻找或多或少的意外⽤途。 我最近写过有关 。 这是另⼀个有趣的例⼦:遍历递归数据结构。
事不宜迟,请看⼀下代码:
class Tree {
private int value;
private List<Tree> children = new LinkedList<>();
public Tree(int value, List<Tree> children) {
super();
改变生活
this.value = value;
this.children.addAll(children);
神舟11号}
public Tree(int value, children) {
this(value, asList(children));
}
public int getValue() {
王力宏新歌return value;
}
public List<Tree> getChildren() {
return Collections.unmodifiableList(children);
}
public Stream<Tree> flattened() {
at(
Stream.of(this),
children.stream().flatMap(Tree::flattened));
}
红星乱紫烟}
除了⼀些突出显⽰的⾏以外,这⾮常⽆聊。
桌面快捷方式图标
假设我们希望能够找到匹配树中某些条件的元素或找到特定元素。 ⼀种典型的实现⽅法是递归函数-但它具有⼀定的复杂性,并且可能需要可变的参数(例如,可以附加匹配元素的集合)。 另⼀种⽅法是使⽤堆栈或队列进⾏迭代。 它们⼯作正常,但是需要⼏⾏代码,⽽且很难⼀概⽽论。
这是我们可以使⽤该flattened函数执⾏的操作:
// Get all values in the tree:
t.flattened().map(Tree::getValue).collect(toList());
中考英语作文题目// Get even values:
t.flattened().map(Tree::getValue).filter(v -> v % 2 == 0).collect(toList());
// Sum of even values:
t.flattened().map(Tree::getValue).filter(v -> v % 2 == 0).reduce((a, b) -> a + b);
// Does it contain 13?
固若金汤打一河北地名
t.flattened().anyMatch(t -> t.getValue() == 13);
我认为该解决⽅案⾮常巧妙且⽤途⼴泛。 ⼀⾏代码(在博客上为了便于阅读,这⾥分成3⾏)⾜以将树扁平化为⼀个简单的流,可以对其进⾏搜索,过滤和其他操作。
但这并不是完美的:它不是惰性的,并且每次都会为树中的每个节点调⽤flattened 。 使⽤Supplier可能会改进它。 ⽆论如何,对于典型的,相当⼩的树⽽⾔,这并不重要,尤其是在⾮常⾼的库堆栈上的业务应⽤程序中。 但是对于⾮常⼤的树,⾮常频繁的执⾏和严格的时间限制,开销可能会带来⼀些⿇烦。粗心英语
翻译⾃: