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>
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With