Search code examples
thymeleaf

How to Filter a list of objects in Thymeleaf on an object Property


I have tried searching on StackExchange and also looked at other places using Google and the Thymeleaf reference as well. It seems like the syntax below should work but it is not filtering the list based on condition given.

<th:block th:each="dayNumber :${#numbers.sequence(1,7)}">
     <p th:if="${#lists.isEmpty(storeHours.?[#this.dayOfWeek eq #dayNumber])}" th:text="${dayNumber}"></p>
</th:block>

In above, we are trying to do a pretty simple filter. The storeHours is a list of Store Hours object. Each object has a property called dayOfWeek. It is an integer. In above, I am trying to simply print the missing day number. However, it is printing all 7 days.

I am sure I am missing something very basic here.

Any help is appreciated.


Solution

  • Try this code :

    <th:block th:each="dayNumber :${#numbers.sequence(1,7)}">
        <p th:if="${#lists.isEmpty(storeHours.?[dayOfWeek.equals(dayNumber)])}" th:text="${dayNumber}"></p>
    </th:block>
    

    Maybe you need to check your storeHours is NOT empty?
    Then ${not #lists.isEmpty(...)}.