recursion list of lists

View: New views
2 Messages — Rating Filter:   Alert me  

recursion list of lists

by PJM :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

If I have a java object that contains a list, which in turn can contain a list...
How would one go about iterating through this list within Velocity, recursively, if possible?

class A
has a STRING s;
and a list of class A objects;

Is there a non-recursive solution?





     

Re: recursion list of lists

by apache-10 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi,

is suspect the depth of your construct is variable. Here some basic programming apporaches (untested code):

Recursive solution:

#macro( process $foo )
  #set( $bar = $foo )## dereference (was needed in Velociry 1.4, don't know if 1.6 still needs this)
  #foreach( $baz in $bar.list )
    ## do something sensible:
    here we are: $baz.s
    ## plunge into the recursion
    #if( $baz.list )#process( $baz )#end
  #end
#end
## call the macro on the root
#process($root)

Non-recursive solution. Since Velocity does not provide a #while directove, I suggest you try to use an ArrayList as stack; it will work if the iterator picks up added elements (to my knowledge it does):

#set( $list = [] )## create an empty ArrayList (performance might be better with a LinkedList or Stack)
$list.add($root)## add root element
#foreach( $baz in $list )
  ## do something sensible:
  here we are: $baz.s
  #if( $baz.list )
    ## insert children at the current list position
    $list.addAll($velocityCount, $baz.list)
    ## in case $bar.list is not of List interface, you will need a macro to loop and add each individual
    ## you might need to adjust $velocityCount by one to insert at the right position...
  #end
  ## now the magic should happen, the foreach iterator should pick up the children...
#end

Hope this helped,
Christoph

Paul M wrote:
> If I have a java object that contains a list, which in turn can contain a list...
> How would one go about iterating through this list within Velocity, recursively, if possible?
>
> class A
> has a STRING s;
> and a list of class A objects;
>
> Is there a non-recursive solution?


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@...
For additional commands, e-mail: user-help@...