Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting elements of arraylist based on index in jstl [duplicate]

Tags:

java

jstl

This is perhaps a relatively simple thing to do but for some reason I don't seem to get it right.

How does one get an element from an arrayList in jstl based on an index.

In pure java, lets say I have this arralist

ArrayList< String > colors = new ArrayList< String >();
   colors.add("red");
   colors.add("orange");
   colors.add("yellow");
   colors.add("green");
   colors.add("blue");

if I do System.out.println(colors.get(1)); I get the first color from the arrayList based on the index I supplied which happens to be red.

Wondering how to achieve that in jstl. I played with the foreach tag in jstl but did not quite get it right.

<c:forEach items="colors" var="element">    
 <c:out value="${element.get(1)}"/>
</c:forEach>
like image 689
tawheed Avatar asked Jun 03 '14 16:06

tawheed


2 Answers

When you say colors.get(1); or ${element[1]} its actually referrign to single entry in the list. But when you use c:forEach its iterating the loop. It depends on what you are trying to achieve. If you just want the Nth element try

<c:out value="${colors[1]}"/> // This prints the second element of the list

but rather you want to print the entire elements you should go for loop like

<c:forEach items="${colors}" var="element">    
    <c:out value="${element}"/>
</c:forEach>

Also please note if you write like <c:forEach items="colors" var="element"> it literally treat the value as "colors". So if its a variable name you need to give it in ${} like ${colors} as depicted in example above.

like image 134
Syam S Avatar answered Nov 15 '22 13:11

Syam S


This should work:

 <c:out value="${colors[0]}"/>

It will print you "red".

But if you want to print all the values of your list, you can use your foreach like that:

<c:forEach items="colors" var="element">    
 <c:out value="${element}"/>
</c:forEach>

This code will iterate over your list colors and set each element of this list in a variable called element. So, element has the same type as the one who parameterized your list (here, String). So you can not call get(1) on String since it does not exist. So you call directly <c:out value="${element}"/> which will call toString() method of your current element.

like image 21
lpratlong Avatar answered Nov 15 '22 12:11

lpratlong