好的,我有这个地图列表:
List data = [
[name: "John", age: 21, gender: "male", option1: "test", option2: "test2"],
[name: "Doe", age: 23, gender: "male", option1: "", option2: "test2"],
[name: "Kate", age: 25, gender: "female", option1: "test", option2: ""],
[name: "Ann", age: 22, gender: "female", option1: "", option2: ""]
]
所以我希望他们像这样分组:
Map<String, Object[]> data = new TreeMap<String, Object[]>()
data.put("1", ["ID", "name", "age", "gender","option1", "option2"])
data.put("2", [1, "John", 21, "male", "test", "test2"])
data.put("3", [2, "Doe", 23, "male", "", "test2"])
data.put("4", [3, "Kate", 25, "female", "test", ""])
data.put("5", [4, "Ann", 21, "female", "", ""])
或者看起来像这样的东西,因为我会将它插入excel文件中。或者,如果有人能够在groovy中推荐一个好方法。
谢谢!
答案 0 :(得分:0)
所以基本的想法是创建一个新的TreeMap
(因为你提到它,但我认为LinkedHashMap
应该就够了),把你的标题行放在那里然后是输入列表中的所有条目,并带有移位索引。
如果您不需要GStrings,请再提示一下,然后使用单引号('
)而不是双引号("
)
在这里,我花了一点时间做了这件事,因为长时间没有开槽,我有点想念这个伟大的语言:
List data = [ [name: "John", age: 21, gender: "male", option1: "test", option2: "test2"], [name: "Doe", age: 23, gender: "male", option1: "", option2: "test2"], [name: "Kate", age: 25, gender: "female", option1: "test", option2: ""], [name: "Ann", age: 22, gender: "female", option1: "", option2: ""] ]
def exportData = [ 1 : [ 'ID', 'name', 'age', 'gender', 'option1', 'option2' ] ] as TreeMap
data.eachWithIndex { it, index -> exportData.put(index+2, [index+1]+it.values()) }
println exportData
试试here。
答案 1 :(得分:0)
另一种选择是创建一个列表列表,前面加上标题名称:
List data = [
[name: "John", age: 21, gender: "male", option1: "test", option2: "test2"],
[name: "Doe", age: 23, gender: "male", option1: "", option2: "test2"],
[name: "Kate", age: 25, gender: "female", option1: "test", option2: ""],
[name: "Ann", age: 22, gender: "female", option1: "", option2: ""]
]
List result = data[0].keySet().with { keys ->
data.inject([keys.toList()]) { curr, next ->
curr << keys.collect { next[it] }
}
}
assert result == [
['name', 'age', 'gender', 'option1', 'option2'],
['John', 21, 'male', 'test', 'test2' ],
['Doe', 23, 'male', '', 'test2' ],
['Kate', 25, 'female', 'test', '' ],
['Ann', 22, 'female', '', '' ]
]