Vignesh Vignesh - 7 months ago 24
Java Question

Java Velocity foreach loop

I have an ArrayList that im populating within java and passing it off to a velocity template for consumption. Now when i try iterating the list and creating a 'comma' separated string from the list, Im observing an erratic behavior.

The following is my code

> #set($list_str="")
> #foreach($item in $list)
> #set($list_str=$!list_str+$!item+",")
> #end


Now i see that my variable $list_str has all the elements of the list but at the end the variable name of the iterator '$!item' is also being appended.

So, say my list has [0,1,2,3,4], my end result(value of $list_str) is [0,1,2,3,4],$!item,


Im not sure if this is because of a null reference from within the list being populated and being passed to the velocity template.

Any pointers towards fixing this would be greatly appreciated.

Thanks

Answer

I did a quick check and this seems to be because of a null value in your ArrayList.

For an ArrayList populated as below --

ArrayList list=new ArrayList();
        list.add("try");
        list.add("to");
        list.add("figure");
        list.add("it");

and with a velocity code as below --

#foreach($iter in $list)
    $!iter
    #set($list_str=$!list_str+$!iter+",")
#end
$!list_str

I get the following output --

try
    to
    figure
    it
try,to,figure,it,

which seems to be as expected.

Now when i populate my Arraylist as follows --

ArrayList list=new ArrayList();
        list.add("try");
        list.add("to");
        list.add("figure");
        list.add("it");
        list.add(null);

and with the same velocty code as above, i get the following output --

try
    to
    figure
    it

try,to,figure,it,$!iter,

So , im guessing that you need to add a null check somewhere in your code to avoid this.

Thanks p1nG

PS: As pointed out by @Thilo Im not sure where the brackets are from, not sure if this is the desired behavior.