java - 从二维数组生成嵌套的 HashMap 列表
问题描述
我想对 进行分组array_list
,如果它的 companyID 相同,则服务("POSID", "POSCODE", "POSTEXT")
应该分组到父级。
public List<HashMap<String,Object>> getList(String [][] array_list) {
ArrayList<HashMap<String,Object>> data = new ArrayList<HashMap<String,Object>>();
/* Example Content String [][] array_list
{ {"4470", "ZONE A", "20", "13", "1", "3800", "Cleaning the table"},
{"4470", "ZONE A", "20, "13"", "2", "3600", "Washing the car"},
{"4470", "ZONE A", "20", "13", "3", "3900", "Preparing the food"},
{"4480", "ZONE B", "10", "9", "1", "3600", "Washing the car"},
{"4480", "ZONE B", "10", "9", "2", "4000", "Dish Washing"},
{"4490", "ZONE C", "5", "4", "1", "3600", "Washing the car"},
{"4490", "ZONE C", "5", "4", "2", "3900", "Preparing the food"}
};
*/
String[] company_fieldnames = new String[] { "COMPANYID", "SECTOR", "AMOUNT", "SIZE" } ;
String[] services_fieldnames = new String[] { "POSID", "POSCODE", "POSTEXT" } ;
for (int i = 0; i < array_list.length; i++) {
HashMap<String, Object> parent = new HashMap<String, Object>();
HashMap<String, Object> child = new HashMap<String, Object>();
for (int j = 0; j < company_fieldnames.length; j++) {
parent.put(company_fieldnames[j], array_list[i][j]);
}
for (int k = 0; k < services_fieldnames.length; k++) {
child.put(services_fieldnames[k], array_list[i][k + company_fieldnames.length]);
}
// TODO
//If same Company ID (4470) then the services should be grouping and pass to the parent element
parent.put("services", child);
data.add(parent);
}
return data;
}
一家公司的结果应如下所示:
[
{
"COMPANYID":"4470",
"SECTOR":"ZONE A",
"AMOUNT":"20",
"SIZE":"13",
"services":[
{
"POSID":"1",
"POSTCODE":"3800",
"POSTEXT":"Cleaning the table"
},
{
"POSID":"1",
"POSTCODE":"3600",
"POSTEXT":"Washing the car"
},
{
"POSID":"3",
"POSTCODE":"3900",
"POSTEXT":"Preparing the food"
}
]
}
]
解决方案
推荐阅读
- java - 在 tools.jar 中哪里可以找到 Treemaker 相关文档
- sql - Laravel 5.6.9 - 数据库计数给出不同的输出
- python - 如何让这段代码更高效(KS测试)
- html - 如何将动态值放入来自 React 中 JSON 文件的 HTML 字符串中?
- mysql - SQL CONSTRAINT UNIQUE 无法插入更多数据
- java - 在一行中记录多件事而不是记录多行有什么好处?
- bash - 在两个字符之间切换
- python - 无法在指数平滑中指定初始化方法
- java - MQTT 和 SpringBoot 集成连接丢失
- swiftui - 在多个堆栈中使用 Image 时如何删除空格?