I want to return a group of groups to n times in the following ways;
[
{
"field": "TestContacts_CompanyName",
"value": "MC 1",
"hasSubgroups": true,
"items": [
{
"field": "TestContacts_ID",
"value": "25",
"hasSubgroups": false,
"items": [
{
"TestContacts_ID": "25",
"TestContacts_CompanyName": "MC 1"
}
]
},
{
"field": "TestContacts_ID",
"value": "26",
"hasSubgroups": false,
"items": [
{
"TestContacts_ID": "26",
"TestContacts_CompanyName": "MC 1"
}
]
},
{
"field": "TestContacts_ID",
"value": "27",
"hasSubgroups": false,
"items": [
{
"TestContacts_ID": "27",
"TestContacts_CompanyName": "MC 1"
}
]
}
]
},
{
"field": "TestContacts_CompanyName",
"value": "MC 2",
"hasSubgroups": true,
"items": [
{ "field": "TestContacts_ID",
"value": "28",
"hasSubgroups": false,
"items": [
{
"TestContacts_ID": "28",
"TestContacts_CompanyName": "MC 2"
}
]
}
]
}
]
I don't want to use collectors.groupingby
public static JSONArray groupedArray(ArrayList<String> groupField,JSONArray itemsArray) throws Exception {
JSONArray itemArrayTemp = new JSONArray();
int i=0;
for (Map.Entry<String,ArrayList<Object>> entry : SLQUtil.groupData(groupField.get(i),itemsArray).entrySet()) {
JSONObject itemTemp = new JSONObject();
itemTemp.put("field",groupField.get(i) );
itemTemp.put("value",entry.getKey() );
if((groupField.size()-i ==1)){
itemTemp.put("hasSubgroups",false );//Single level grouping
itemTemp.put("items",entry.getValue() );
}else if((groupField.size()-i > 1)){
itemTemp.put("hasSubgroups",true );//2nd level grouping
JSONArray jsArray2 = new JSONArray(entry.getValue());//converting array list to json array
JSONArray itemArrayTemp2 = new JSONArray();
for (Map.Entry<String,ArrayList<Object>> entry2 : SLQUtil.groupData(groupField.get(i+1),jsArray2).entrySet()) {
JSONObject itemTemp2 = new JSONObject();
itemTemp2.put("field",groupField.get(i+1));
itemTemp2.put("value",entry2.getKey() );
itemTemp2.put("hasSubgroups",false );
itemTemp2.put("items",entry2.getValue() );
itemArrayTemp2.put(itemTemp2 );//2nd level of grouped data
}
itemTemp.put("items",itemArrayTemp2 );
}
itemArrayTemp.put(itemTemp);//1st level of grouped data
}
return itemArrayTemp;
}
public static Map<String, ArrayList<Object>> groupData(String field,JSONArray itemsArray) throws Exception {
Map<String, ArrayList<Object>> itemMap = new LinkedHashMap<>();
for (int i=0;i<itemsArray.length();i++){
JSONObject itemTemp = itemsArray.getJSONObject(i);
if(!itemMap.containsKey(itemTemp.getString(field))){
itemMap.put(itemTemp.getString(field), new ArrayList<>());
}
itemMap.get(itemTemp.getString(field)).add(itemTemp);
}
return itemMap;
}