I'm looking for a suitable recursive way to achieve the following: An Element A can have a List L1 which contains further Elements such as A, e.g. B,C and D. These Elements (B,C and D) can have a List L2, L3, L4 too. So I need to go through these Lists too. The Background is that I want to get all Objects from all Lists of all Elements which contains "LB" at the End of their name (retrieved by getName()). All Objects of the Lists have the same Type. How I do achieve this? As I don't know how many Elements and Lists there will be, I think the recursive solution is the only proper one?
2 Answers
Basically you have a tree structure there, which means you probably need some form of tree traversal. Let's assume we have this tree-like structure:
class Node<T>{
T value;
List<Node<T>> children = new ArrayList<>();
}
Now, if you want to apply a callback C to each of these nodes, you will do something like this:
public <T> void visit(Node<T> rootNode, Consumer c){
c.consume(rootNode.value);
rootNode.children.forEach(n -> visit(n, c));
}
This is called a depth-first traversal.
3 Comments
BlackACE
Wow thats seems pretty hard to implement. How would I fill this tree with my data and how would I search a node within this tree?
sotix
@BlackACE: Look up tree implementations in Java, there should be plenty online.
Sean Patrick Floyd
@sotix +1. I'd suggest Guava's
TreeTraverser classYou can use flatmap: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#flatMap-java.util.function.Function-
Which "flatten" the List/Array.
Eg:
l1.stream().flatMap(Collection::stream).map(e-> e.getName()).filter(e -> e.contains("LB")).collect(Collectors.joining());
1 Comment
Sean Patrick Floyd
This works well with one level of nesting, but not with arbitrary depth