How do I iterate over Java object (object A --> member arraylist --> of object A to create tree structure in JSP

webbie79
webbie79 used Ask the Experts™
on
I need to iterate on a java object, preferrablt using JSTL (c:foreach or similar)
The java object is as follows: -

Object A has arraylist of Object A, I need to iterate and execute code for each object A in JSP

Object A {
ArrayList of Object A
}

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Mick BarryJava Developer
Top Expert 2010

Commented:

     

where all is the name of the Object A instance
and list is the name of the ArrayList property

Author

Commented:
Thanks for your quick response.

How does  <c:forEach var="a" items="${all.list}"> work, when the indentation inside the object is unlimited.
For instance,
1) Parent Object A --> has Arraylist of Object A <-- Child Object
2) Child Object A --> again has Arraylist of Object <-- granchildren
3) and so on..
there could be n. number of indentation here.

Will this work in this case? let me know.. thanks for your time in advance
 
Mick BarryJava Developer
Top Expert 2010
Commented:
you can have as many levels as you want, just name the properties of the bean that you want to access.

> Will this work in this case?

you would need a second loop to access the grandchildren

     
         
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

Author

Commented:
What if we don't know the depth of the tree before hand. From the code above, it looks like, one needs to introduce a <c:forEach> loop for each indentation.
At the start, if we dont know the depth of the tree, then how do we decide how many foreach loops are needed here.
Is there a tag like c:while - which could run <c:forEach> for each level. I am sorry if I sound off track here.
Mick BarryJava Developer
Top Expert 2010

Commented:
you would need to know the # levels and properties in advance

Author

Commented:
Ok. I think it works now. Here is what I have done: -

1. Get the tree depth from the database as separate property and implemented the following: -

<c:forEach var="i" begin="1" end="${a.treeDepth}">
  <c:forEach var="a" items="${a.childList}" varStatus="counter">
  </c:forEach>
</c:forEach>
The outer loop spins for the tree depth and the inner loop prints all the childs at each level.

Any expert comments?

Mick BarryJava Developer
Top Expert 2010
Commented:
thats just going to loop over childList multiple times
Commented:
I think it should work for me, in case it doesn't, i'll come bug you again. Thanks a lot for your help.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial