Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if list of objects contains a String using thymeleaf?

Say if I have an ArrayList with user objects into it.

User.java

class User{
  private Long id;
  private String name;
}

I have a list with users

list.add(new User(1,"John");
list.add(new User(2,"Sam");

I want to check in thymeleaf if user List is having a user with name "Sam".

${#lists.contains(userList.name,'Sam')}

But the above doesn't work and throws Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression

I've also tried with " (doube-quotes)

like image 382
Lucky Avatar asked Oct 12 '16 10:10

Lucky


1 Answers

You can achieve this using the Collection Selection feature of Spring Expression Language.

10.5.17 Collection Selection

Selection is a powerful expression language feature that allows you to transform some source collection into another by selecting from its entries.

Selection uses the syntax ?[selectionExpression]. This will filter the collection and return a new collection containing a subset of the original elements.

In your particular case it would be:

${not userList.?[name == 'Sam'].isEmpty()}
like image 153
Tobías Avatar answered Sep 28 '22 14:09

Tobías