You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Thymeleaf中访问HashMap元素获取Network Id的问题

Solution for Accessing Any HashMap Element's Network Id in Thymeleaf

Got it, let's fix this Thymeleaf expression issue. Since all entries in your poolHashrates HashMap share the same networkHashrate.id, we just need to grab any entry's value from the map—no need to target a specific key. Here's how to do it correctly:

Working Expressions

Pick one of these based on your preference:

  1. Using Collection Iterator (Simple & Direct)
    This grabs the first value from the map's value collection (since all IDs are identical, order doesn't matter):

    th:text="'Network Id: ' + ${poolHashrates.values().iterator().next().networkHashrate.id}"
    
  2. Using Stream API (Modern Java Style)
    If you prefer more explicit stream operations (works with Spring EL support):

    th:text="'Network Id: ' + ${poolHashrates.values().stream().findFirst().get().networkHashrate.id}"
    
  3. Safe Version (Handle Empty Map)
    To avoid NoSuchElementException if the map might be empty, add a null/empty check:

    th:text="'Network Id: ' + ${poolHashrates.isEmpty() ? 'N/A' : poolHashrates.values().iterator().next().networkHashrate.id}"
    

Why Your Previous Attempts Failed

Let's break down where you went wrong:

  • ${poolHashrates[0].key.networkHashrate.id}: HashMaps aren't indexed by default (unless using LinkedHashMap with specific configuration), so [0] doesn't work here. Also, key refers to the entry's key, not a property of the value—so this path is invalid.
  • ${poolHashrates.get(key)}: This would work only if key is a variable present in your Thymeleaf context (e.g., from a loop or model attribute). But since you don't need a specific key, this approach is unnecessary for your use case.

内容的提问来源于stack exchange,提问作者Maciaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:22:19