Search code examples
javajsparrayliststruts2ognl

Iterating through two ArrayLists parallell in struts2


I have two Array lists

private ArrayList<String> userPics = new ArrayList<String>();
private ArrayList<String> picLikes = new ArrayList<String>();

The first arraylist contains the paths of the image and the other list contains the no.of likes each picture got. i need to get the value in parallel in struts2 using the iterator tag. How to do it..?


Solution

  • Assuming you are "linking" them with the index, you can use IteratorStatus like follows:

    <s:iterator value="userPics" var="pics" status="ctr">
        Current Element from userPics: <s:property value="pics" />
        Current Element from picLikes: <s:property value="picLikes[%{#ctr.index}]" />
    </s:iterator>
    

    But it would be 10 times better to create an object with those two attributes, and a List of them:

    public class Picture {
        private byte[] picture;
        private int likes;
        /* getters and setters */
    }
    

    then in your Action:

    private List<Picture> pics;
    /* getter and setter */
    

    and finally in your JSP:

    <s:iterator value="pics">
        Current Element from userPics: <s:property value="picture" />
        Current Element from picLikes: <s:property value="likes" />    
    </s:iterator>