Home > Blockchain >  Iterating through a List<Map<String, Object>> map in Thymeleaf
Iterating through a List<Map<String, Object>> map in Thymeleaf

Time:03-22

Hello I haven 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 ?

Thanks in advance

CodePudding user response:

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>

CodePudding user response:

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>
  • Related