The Thymeleaf documentation states about sorting lists:
/*
* Sort a copy of the given list. The members of the list must implement
* comparable or you must define a comparator.
*/
${#lists.sort(list)}
${#lists.sort(list, comparator)}
In my document model, I have a list of maps with key value pairs (the published_content
list from the JBake static page generator). In my template, I want to sort this list by comparing the value stored under a certain key in the maps.
In other words, the list
variable has type List<Map<String, Object>>
and I want to sort this list by comparing the value in each map stored under the key "mykey"
.
How can I formulate such a comparator in the template?
The question is more related to a pure Java sorting issue, as you need a way to sort a list of maps, this was already answered here .
Related code:
public Comparator<Map<String, String>> mapComparator = new Comparator<Map<String, String>>() {
public int compare(Map<String, String> m1, Map<String, String> m2) {
return m1.get("name").compareTo(m2.get("name"));
}
}
Collections.sort(list, mapComparator);
After having your list sorted working, using mapComparator, you could use the Thymeleaf expression ${#lists.sort(list, comparator)}
as explained in the docs.
In Thymeleaf you need to use the full classname (include package). Something like:
<span th:each="doc : ${#lists.sort(documents, new com.mycompany.myapp.comparator.DocumentNameComparator())}">
...
</span>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.