【问题标题】:How to access an object key in Map without iterating in Thymeleaf如何在不迭代 Thymeleaf 的情况下访问 Map 中的对象键
【发布时间】:2019-01-19 20:09:43
【问题描述】:

我有一个 java 类 Result,它包含一个名为 results 的变量,它是一个 HashMap

public class Result {

   private HashMap<Class1, Class2> results = new HashMap<>();

}

我正在使用一个名为 Class1 的对象作为上述 HashMap 的键。

public class Class1 {

   private String attribute1;

   private String attribute2;

   private String attribute3;

   private String attribute4;

}

在前端,我以下面的方式迭代了 HashMap 并访问了值。

<span th:each="result : ${results}" th:if="${#strings.equals('SOME_VALUE', result.key.attribute1)}" th:text="${result.value.someAttribute}"/>

使用上面的 thymeleaf 代码,我得到了预期的结果。但我需要知道有没有最简单的方法来访问 HashMap 值而不像这样迭代?我正在使用 thymeleaf 3.0.0.RELEASE 版本。

【问题讨论】:

  • 您想在 Java 中迭代 Map 还是在 thymeleaf 中拥有不同的迭代风格?
  • 我需要知道是否有任何方法可以访问结果而不会影响 thymeleaf。
  • 有几种方法可以在 Java 中迭代 Map。您可以遍历键集,使用 Iterator 类或仅应用 lambda 表达式,如 map.forEach。我不知道百里香本身是否有替代品......
  • hashcode() 和 equals() 方法应该在 Class1 中实现

标签: java spring-boot thymeleaf


【解决方案1】:

您可以为此使用collection selection

<span th:text="${results.^[key.attribute1 == 'SOME_VALUE'].values()[0].someAttribute}"/>

results.^[key.attribute1 == 'SOME_VALUE'] 返回一个带有单个元素的HashMap(在我看来,这应该返回一个Map.Entry,但事实并非如此)。然后我调用values()HashMap 上的一个函数,它将 HashMap 中的值作为Collection 返回),[0] 返回该Collection 中的第一个元素。

【讨论】:

  • 这是预期的答案。谢谢。请你解释一下 values()[0] 的用法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
  • 2020-03-27
  • 2018-02-25
相关资源
最近更新 更多