我有这个课:

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
                }
            });
        }
    });
}

最佳答案

进行递归调用:

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)所说,您可以将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()));

关于java - 遍历集合中的集合直到Java中的最后一个元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48186149/

10-09 09:27