如何在Freemarker中遍历三层嵌套的Map集合
Hey there, let's walk through how to handle that three-level nested Map<String, Map<String, Map<String,String>>> in FreeMarker—covering both full traversal of all entries and direct key-based lookups.
Three-Level Nested Map Handling in FreeMarker
1. Full Traversal of All Entries
If you need to iterate through every key-value pair across all three levels, use FreeMarker's <#list> directive with the ?entry_set method (which gives you the key-value pairs of a Map). We'll also add null/empty checks to avoid runtime errors.
<#-- Iterate over the first-level Map --> <#list map?entry_set as firstLevelEntry> <h3>First Level Key: ${firstLevelEntry.key}</h3> <#-- Grab the second-level Map and check if it's not empty --> <#assign secondLevelMap = firstLevelEntry.value> <#if secondLevelMap?has_content> <#list secondLevelMap?entry_set as secondLevelEntry> <h4> Second Level Key: ${secondLevelEntry.key}</h4> <#-- Grab the third-level Map and check if it's not empty --> <#assign thirdLevelMap = secondLevelEntry.value> <#if thirdLevelMap?has_content> <ul> <#list thirdLevelMap?entry_set as thirdLevelEntry> <li> Third Level Key: ${thirdLevelEntry.key} | Value: ${thirdLevelEntry.value}</li> </#list> </ul> <#else> <p> Third-level Map is empty</p> </#if> </#list> <#else> <p> Second-level Map is empty</p> </#if> </#list>
Key Notes:
?entry_set: Converts a Map into a collection of key-value entry objects (each haskeyandvalueproperties).?has_content: Checks if the Map is non-null and not empty—prevents errors when a nested Map doesn't exist.- Indentation (using
or nested HTML elements) helps visualize the hierarchy in the output.
2. Direct Lookup via Specified String Keys
If you know the exact keys for each level and just need to fetch the final value, you can chain key accesses. Use ?default({}) to handle cases where a nested Map doesn't exist (avoids null pointer exceptions).
<#-- Define your target keys --> <#assign firstLevelKey = "user"> <#assign secondLevelKey = "profile"> <#assign thirdLevelKey = "email"> <#-- Chain the lookups with fallbacks --> <#assign finalValue = map[firstLevelKey]?default({})[secondLevelKey]?default({})[thirdLevelKey]?default("Value not found")> <p>Target Value: ${finalValue}</p>
Key Notes:
map[key]: Accesses the value associated withkeyin the Map—works just like Java'smap.get(key).?default({}): If the previous level's Map is null or doesn't exist, it returns an empty Map instead, so the next lookup doesn't fail.- The final
?default("Value not found")provides a fallback string if the third-level key doesn't exist.
内容的提问来源于stack exchange,提问作者devtest
相关产品推荐
相关产品推荐

