首页 > 解决方案 > 从二维数组生成嵌套的 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"
             }
          ]
       }
    ]

标签: javaloopsmultidimensional-arrayhashmap

解决方案


推荐阅读