在Thymeleaf中访问HashMap元素获取Network Id的问题
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:
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}"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}"Safe Version (Handle Empty Map)
To avoidNoSuchElementExceptionif 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 usingLinkedHashMapwith specific configuration), so[0]doesn't work here. Also,keyrefers to the entry's key, not a property of the value—so this path is invalid.${poolHashrates.get(key)}: This would work only ifkeyis 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

