0

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?

1
  • Your lists will be stored as class properties or they will be in a root List ? Commented Jun 28, 2016 at 10:11

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
@BlackACE: Look up tree implementations in Java, there should be plenty online.
@sotix +1. I'd suggest Guava's TreeTraverser class
0

You 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

This works well with one level of nesting, but not with arbitrary depth

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.