1

I have built an application in Spring-MVC with Thymealeaf and I would like to iterate in a table in Thymealeaf the DB entries.

This is the object that I am iterating:

List<Map<String, Object>> map

I tried this code in Thymleaf:

<table>
<tr>
<td> CNP:</td>
<td th:text ="${raspuns.cif}" ></td>
</tr>
<tr>
<td> Nume:</td>
<td th:text ="${raspuns.den_client}" ></td>
</tr>

</table>

But it shows only 2 entries and I know it has 311 or something like that. How could I iterate through all the entries and show them all?

2
  • The template you have shown to us does not include any iteration and it also does not access map. We won't be able to help without this information. Commented Mar 22, 2022 at 8:30
  • I was hoping someone could give me an example on how to iterate on a List<Map<String, Object>> Commented Mar 22, 2022 at 8:34

2 Answers 2

2

You have to iterate list first, and then read each map from list & then read map object with the help of key like this:

Java Code:

List<Map<String, String>> mapList = new ArrayList<>();

Map<String, Object> firstMap = new HashMap<>();
firstMap.put("id", "1");
firstMap.put("name", "test_name_1");

Map<String, Object> secondMap = new HashMap<>();
secondMap.put("id", "2");
secondMap.put("name", "test_name_2");

mapList.add(firstMap);
mapList.add(secondMap);

model.put("map_list", mapList);

Thymeleaf Code:

<tr th:each="map : ${map_list}">
<td> CNP:</td>
<td th:text ="${map.get('id')}" ></td>
<td> Nume:</td>
<td th:text ="${map.get('name')}" ></td>
</tr>
Sign up to request clarification or add additional context in comments.

Comments

0

You should first iterate through the list then iterate through the map to access the keys and values.

To simplify the process, a suggestion would be to convert your List<Map<String,Object>> to Map<String, Object> like so:

Map<String, Object> result = map
                .stream()
                .collect(Collectors.toMap(s -> (String) s.get("key"),
                                          s -> s.get("value")));

Then you may want to iterate through the map:

<table>
   <tr>
      <th> CNP:</th>
      <th> Nume:</th>
   </tr>
   <tr each:="entry: ${map}">
      <!-- You can access a {key, value} pair for each entry of the map -->
      <td th:text ="${entry.key}" ></td>
      <td th:text ="${entry.value}" ></td>
   </tr>
</table>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.