我有这堂课:
public class SimpleEntity {
private String id;
private String name;
private boolean closed;
private List<SimpleEntity > simpleEntityChildren;
}
我希望以递归方式迭代到SimpleEntityChildren
,直到最后一个元素,我不知道如何实现它。
public void iterator(SimpleEntity simpleEntity ){
simpleEntity .forEach(entity-> {
if(!entity.getSimpleEntityChildren.isEmpty()){
entity.forEach(secondEntity-> {
if(!secondEntity.getSimpleEntityChildren.isEmpty()){
//and so on to the last element
}
});
}
});
}
答案 0 :(得分:3)
进行递归通话:
public void iterate(SimpleEntity entity) {
// you might want to add some logic here, that actually does something
// with the current SimpleEntity instance you are iterating over
for (SimpleEntity child : entity.getSimpleEntityChildren()) {
iterate(child);
}
}
请注意,如果所有StackOverflowError
个实例的图表中都有循环,则会导致无限递归和SimpleEntity
。
正如Boris评论的那样,您可以传递方法a Consumer<SimpleEntity>
,其中包含要在每个SimpleEntity
实例上执行的逻辑。
public void iterate(SimpleEntity entity, Consumer<SimpleEntity> consumer) {
consumer.accept(entity);
for (SimpleEntity child : entity.getSimpleEntityChildren()) {
iterate(child,consumer);
}
}
例如,您可以递归方式打印给定SimpleEntity
实例的层次结构中所有SimpleEntity
个实例的名称:
SimpleEntity someEntity = ...
iterate(someEntity, e -> System.out.println(e.getName()));
您还可以添加非递归方法来启动迭代过程:
public void iterate(Consumer<SimpleEntity> consumer) {
iterate(this,consumer);
}
现在你可以写:
SimpleEntity someEntity = ...
someEntity.iterate(e -> System.out.println(e.getName()));
答案 1 :(得分:1)
您可以使用递归方法。
public void iterator(SimpleEntity simpleEntity ){
simpleEntity .forEach(entity-> {
iterator(entity);
});
}
答案 2 :(得分:0)
最佳方法是:
1. 将您的主班级更改为:
public class SimpleEntity {
private String id;
private String name;
private boolean closed;
private List<SimpleEntity > simpleEntityChildren;
public Stream<Tree> flattened() {
return Stream.concat(
Stream.of(this),
simpleEntityChildren.stream().flatMap(Tree::flattened));
}
}
2. 然后简单地迭代它:
public void iterator(SimpleEntity simpleEntity) {
simpleEntity.flattened().forEach(entity->{
// Do whatever you want
});
}