Thymeleaf is flexible in many ways. When it comes to interations, you can use not only java.util.List objects but also any other collection that implements java.util.Iterable or java.util.Enumeration or java.util.Iterator or java.util.Map interface. We can simply use th:each in our case, to loop through Map. Note that the iteration variable will be of class java.util.Map.Entry.
Let's start our example with a simple model that presents the Car:
The color will be a simple enum of three values: RED, WHITE, BLACK.
The controller class provides two maps:
with cars grouped by the color,
with cars grouped by production year.
Thymeleaf template that iterates over those two Maps will have the following structure:
Note that in our case ${entry.value} will point to the collection of specific Car objects grouped by provided attribute.
3. Conclusion
In this tutorial, we showcased the simple example of how to loop through Map in Thymeleaf. We use a map when a key is a color or a year of production and the value is a collection of aggregated cars.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}