java - 如何在 FTL(Freemarker) 中创建地图列表
问题描述
我有一个列表地图,testMap
里面的列表有一个地图列表testMap
。
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 模板错误:对于 ""."" 左侧操作数:应为哈希,但这已评估为序列(包装器:ftSimpleSequence):
我不知道我怎样才能做到这一点。任何帮助,将不胜感激。
解决方案
模板语言不是为做这些事情而设计的。您应该将此因素考虑到您从模板中调用的 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 是其中的顶级键的数量。这就是为什么那里没有很多钥匙很重要的原因。
在调用add
/put
时,通常是不可能的。一种解决方法是添加一个实用程序来创建新 ArrayList
的or LinkedHashMap
,然后您可以使用myList?api.add(...)
等。在那里,?api
允许您访问 Java API。但同样不适用于使用[]
or创建的值{}
;无论如何,这些都不是可变的集合。
推荐阅读
- sql - 加入 2 个 oracle 查询
- python - Tesseract OCR 错误,可能是因为 traineddata
- vba - 当用户在 Outlook 中更改会议日期(不打开加载项)时,如何向我的加载项发送请求?
- mysql - 在 where 子句中创建别名并按子句顺序使用该别名
- javascript - 从 SP2013 迁移到 SP2019 时 jQuery 代码不起作用
- javascript - 角度对象到对象数组
- angular - How to call a service from ag grid drag & drop event
- python - 抑制由 python (.pyw) 脚本中的子进程打开的 shell
- docker - Dockerfile:如何在运行时将 en 变量传递给入口点数组
- abap - 当你有“string”类型时,为什么ABAP中有这么多“char”类型?