Generic Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

If you have a few years of Linux experience, and you're interested in sharing that with the community (and getting paid for your work of course), have a look at the "Write for Us" page. Cheers. Eugen

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.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

Leave a Reply

avatar
  Subscribe  
Notify of