我有一张列表 testMap
的 map 以及 testMap
内的列表有一个 map 列表。
testMap = {"list1": list1, "list2" : list2}
list1 = [{"key" : value, "key" : value1},{"key" : value, "key" : value1}]
list2 = [{"key" : value, "key" : value1},{"key" : value, "key" : value1}]
我想根据列表中键的值将 testMap 分成 2 个映射 testMap1 和 testMap2。
这是我尝试过的
<#assign testMap1 = {}>
<#assign testMap2 = {}>
<#list testMap?keys as key>
<#assign testMapList = testMap[key]>
<#assign testList1 = []>
<#assign testList2 = []>
<#list testMapList as testList>
<#if actionMap["key1"]??>
<#if actionMap["key1"] == "test">
<#assign ignore = testList1.add(testList)>
<#elseif actionMap["key1"] == "test1>
<#assign ignore = testList2.add(testList)>
</#if>
</#if>
</#list>
<#if testList1?has_content>
<#assign ignore = testMap1.put(key, testList1)>
<#elseif testList2?has_content>
<#assign ignore = testMap2.put(key, testList2)>
</#if>
</#list>
但是<#assign ignore = testList1.add(testList)>
此行抛出错误
"FreeMarker template error: For ""."" left-hand operand: Expected a hash, but this has evaluated to a sequence (wrapper: f.t.SimpleSequence):
我不知道如何才能实现这一目标。任何帮助将不胜感激。
最佳答案
模板语言不是为做这样的事情而设计的。您应该将其分解到一个 Java 实用程序中,并从模板中调用该实用程序。或者,如果无论表示(格式)如何,这种重组都有意义,则将数据放入已经这样结构化的数据模型中。
但是...如果您确实必须在模板内执行此操作,并且 testMap
没有很多键:
<#assign testMap1 = {}>
<#assign testMap2 = {}>
<#list testMap as k, v>
<#assign map1V = v?filter(it -> it.key1 == 1)>
<#if map1V?size != 0>
<#assign testMap1 = testMap1 + {k: map1V}>
</#if>
<#assign map2V = v?filter(it -> it.key1 != 1)>
<#if map1V?size != 0>
<#assign testMap2 = testMap2 + {k: map2V}>
</#if>
</#list>
读取生成的两个映射将O(N)
慢,其中N是其中顶级键的数量。这就是为什么不要有太多 key 很重要的原因。
从调用add
/put
开始,通常是不可能的。一种解决方法是添加一个实用程序来创建新ArrayList
或LinkedHashMap
,然后您可以使用myList?api.add(。 ..)
等等。在那里,?api
允许您访问 Java API。但同样不适用于使用 []
或 {}
创建的值;无论如何,这些都不是可变的集合。
关于java - 如何在FTL(Freemarker)中创建 map 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60630216/