Search code examples
thymeleafguava

How to iterate Guava multimap in thymleaf


I have below map collection. I want to iterate this in thymeleaf but getting below error.

Multimap<String,String> map = ArrayListMultimap.create();

<div th:each="m : ${menu.entries}">

EL1008E: Property or field 'entries' cannot be found on object of type 'com.google.common.collect.ArrayListMultimap' - maybe not public or not valid?


Solution

  • Here is one way of iterating a Guava multimap in Thymeleaf.

    Some test data:

    Multimap<String, String> map = ArrayListMultimap.create();
    map.put("key one", "value one");
    map.put("key two", "value two a");
    map.put("key two", "value two b");
    map.put("key three", "value three");
    

    The Thymeleaf:

    <div th:each="k : ${menu.keySet()}">
        <div th:text="'key is: ' + ${k}">
        </div>
        <div th:each="v : ${menu.get(k)}">
            <div th:text="'val is: ' + ${v}">
            </div>
        </div>
    </div>
    

    This gives the following output in the web page (ordering is not guaranteed):

    key is: key two
    val is: value two a
    val is: value two b
    key is: key one
    val is: value one
    key is: key three
    val is: value three