Based on your question I have a map like this:
HashMap<Integer, Integer[]> map = new HashMap<>();
map.put(2002, new Integer[]{201, 1004, 200});
map.put(2003, new Integer[]{1002, 311, 902, 312});
map.put(2001, new Integer[]{305, 304, 322, 900, 317, 301, 319, 302, 318, 303});
map.put(201, new Integer[]{203, 202});
map.put(203, new Integer[]{204});
map.put(2004, new Integer[]{310, 109});
map.put(202, new Integer[]{121});
map.put(2005, new Integer[]{1000, 1003, 116, 504, 115, 505, 114, 1010, 502, 108, 503, 107});
To create the nested structure I will use a recursive method:
For the given keyValue I retrieve all values and look if they are a key in the map. If they are, I call the same method again with the value as keyValue, otherwise I will just return the value as it is a leaf.
private JSONArray createJSONArray(HashMap<Integer, Integer[]> map, int keyValue) {
Integer[] values = map.get(keyValue);
JSONArray arr = new JSONArray();
if(values != null){
for(int val: values){
if(map.containsKey(val)){
JSONObject jObj = new JSONObject();
jObj.put(Integer.toString(val), createJSONArray(map, val));
arr.put(jObj);
}
else{
arr.put(val);
}
}
}
return arr;
}
To create a complete JSONObject with the top-level keys, I run the method above in a loop with the top-level values as keyValue:
JSONObject jObj = new JSONObject();
for(int key: new int[]{2002, 2003, 2000, 2001, 2004, 2005, 999}){
jObj.put(Integer.toString(key), createJSONArray(map, key));
}
This will result in the following, which is hopefully the format you wanted:
{
"2004": [ 310, 109 ],
"2005": [ 1000, 1003, 116, 504, 115, 505, 114, 1010, 502, 108, 503, 107 ],
"2002": [ {"201": [ {"203": [204] }, {"202": [121] } ] }, 1004, 200 ],
"2003": [ 1002, 311, 902, 312 ],
"2001": [ 305, 304, 322, 900, 317, 301, 319, 302, 318, 303 ],
"999": [],
"2000": []
}