How to get the first item on the jsp page from the Map .

 Map<Long,MyObject> map = ...... model.addAttribute("statuses", map); 

There is such a code on the JPS page.

 <c:set var="myvalue" value="${statuses[0].value.myfield}"/> //error <c:forEach var="status" items="${statuses}"> .... </c:forEach> 

How to get the first element that will be in a forEach loop?

  • Not quite clear. Do you want to iterate over your hash table? - Pavel Parshin

3 answers 3

Right here

 model.addAttribute("firstStatus", CollectionUtils.first(map.values())); 

CollectionUtils.first() can be implemented or searched in libraries.

Yes, and we must bear in mind that the concept of the first element strongly depends on the implementation of the Map .

  • It is not a good idea to add additional data to the model. It would be perfect to solve without it. - Vurtatoo
  • @Vurtatoo I prefer the rule - JSP for markup and only. Additional designs only as a last resort. - v.ladynev

You can try this:

 <c:forEach var="status" items="${statuses}" begin="0" end="0"> .... </c:forEach> 

That is, according to your collection, only one iteration will be performed on the first element.

If the remaining elements of the collection are subject to processing, then the first element can be checked through c:if and c:forEach ... varStatus="status" . Similar question with status variable here

PS The code did not check, but the idea should be clear.

    If the Map implementation is not important, then you can take a specific implementation instead of an interface. For example, a TreeMap that implements the firstEntry method.

    On the jsp page, a type casting is required to invoke the method.