1. Overview
Thymeleaf is a Java template engine for processing and creating HTML.
In this quick tutorial, we’ll look into Thymeleaf’s lists utility object to perform common list-based operations.
2. Computing Size
First, the size method returns the length of a list. We can include it, say, via the th:text attribute:
size: <span th:text="${#lists.size(myList)}"/>
myList is our own object. We’d have passed it via the controller:
@GetMapping("/size") public String usingSize(Model model) { model.addAttribute("myList", getColors()); return "lists/size"; }
3. Checking if the List is Empty
The isEmpty method returns true if the given list has no elements:
<span th:text="${#lists.isEmpty(myList)}"/>
Generally, this utility method is used with conditionals – th:if and th:unless:
<span th:unless="${#lists.isEmpty(myList)}">List is not empty</span>
4. Checking Membership
The contains method checks whether an element is a member of the given list:
myList contains red: <span th:text="${#lists.contains(myList, 'red')}"/>
Similarly, we can check the membership of multiple elements using the containsAll method:
myList contains red and green: <span th:text='${#lists.containsAll(myList, {"red", "green"})}'/>
5. Sorting
The sort method enables us to sort a list:
sort: <span th:text="${#lists.sort(myList)}"/> sort with Comparator: <span th:text="${#lists.sort(myList, reverse)}"/>
Here we have two overloaded sort methods. Firstly, we’re sorting our list in the natural order – ${#lists.sort(myList)}. Secondly, we’re passing an additional parameter of type Comparator. In our example, we’re getting this comparator from the model.
6. Converting to List
Lastly, we can convert Iterables and arrays to Lists using the toList method.
<span th:with="convertedList=${#lists.toList(myArray)}"> converted list size: <span th:text="${#lists.size(convertedList)}"/> </span>
Here we’re creating a new List, convertedList, and then printing its size with #lists.size.
7. Summary
In this tutorial, we’ve investigated the Thymeleaf built-in lists utility object and how to use it effectively.
As always, the source code for all examples is available on GitHub.