Getting index based arraylist elements in jstl

This is perhaps a relatively simple thing, but for some reason I don't seem to understand it.

How to get element from arrayList in jstl based on index.

In pure java, let's 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 arrayList based index I, which matches red .

Think about how to achieve this in jstl. I played with the foreach tag in jstl, but didn't quite understand.

 <c:forEach items="colors" var="element"> <c:out value="${element.get(1)}"/> </c:forEach> 
+6
source share
3 answers

When you say colors.get(1); or ${element[1]} , it actually refers to one entry in the list. But when you use c:forEach , it iterates through the loop. It depends on what you are trying to achieve. If you just want the Nth element to try to execute

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

but you want to print all the elements you should use for the loop, for example

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

Also note that if you write as <c:forEach items="colors" var="element"> , it literally treats the value as "colors" . Therefore, if this is a variable name, you must specify it in ${} as ${colors} , as shown in the example above.

+14
source

This should work:

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

He will print you in red.

But if you want to print all the values โ€‹โ€‹of your list, you can use your foreach as follows:

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

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

+1
source

You can use array based access as follows:

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

Source: https://habr.com/ru/post/970253/


All Articles