I have a java class Result and It contains a variable called results and it is a HashMap.
public class Result {
private HashMap<Class1, Class2> results = new HashMap<>();
}
I'm using an object called Class1 as the key for above HashMap.
public class Class1 {
private String attribute1;
private String attribute2;
private String attribute3;
private String attribute4;
}
In front end I iterated the HashMap in below way and access the values.
<span th:each="result : ${results}" th:if="${#strings.equals('SOME_VALUE', result.key.attribute1)}" th:text="${result.value.someAttribute}"/>
Using above thymeleaf code I got the expected result. But I need to know Is there any easiest way to access the HashMap values without iterating like this? I'm using thymeleaf 3.0.0.RELEASE version.
You can use collection selection for this:
<span th:text="${results.^[key.attribute1 == 'SOME_VALUE'].values()[0].someAttribute}"/>
results.^[key.attribute1 == 'SOME_VALUE']
returns a HashMap
with a single element in it (it seems to me this should return a Map.Entry
, but it doesn't). I then call values()
(a function on HashMap
that returns the values in the HashMap as a Collection
) and [0]
returns the first element in that Collection
.