原数据示例:
[
"captcha_codes:aa:8d5b358a4f45489f93402cd0763abecf",
"captcha_codes:aa:05c8c64e10f24f3caf4944c4340b4204",
"captcha_codes:aa:974901e83d3a46468f98c5e1b6de43ee",
"captcha_codes:aa:2f0bbf64a57a4e8e8dcec88074c45529",
"captcha_codes:aa:c970d8a40ace4b39b77b6dfed8547a49",
"captcha_codes:aa:0509d6f633e541f7a9bb975cebd8acab"
]
/**
* 将keys组装成树结构
* @param keys 原key集合
* @param parentKey 上级节点key
* @return
*/
public JSONArray buildKeys(Collection<String> keys, String parentKey) {
JSONArray jsonArray = new JSONArray();
Map<String, List<String>> single = keys.stream().filter(o->o.split(":").length==1)
.collect(Collectors.groupingBy(o -> o.split(":")[0]));
for (String key : single.keySet()) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("label", key);
jsonObject.put("value", StringUtils.isNotBlank(parentKey)?parentKey+":"+key:key);
jsonArray.add(jsonObject);
}
Map<String, List<String>> map = keys.stream().filter(o->o.split(":").length>1)
.collect(Collectors.groupingBy(o -> o.split(":")[0]));
for (String key : map.keySet()) {
JSONObject jsonObject = new JSONObject();
if (map.get(key).size()>1) {
jsonObject.put("label", key);
jsonObject.put("value", StringUtils.isNotBlank(parentKey)?parentKey+":"+key:key);
List<String> newKey = map.get(key).stream().map(o->o.replace(key+":", "")).collect(Collectors.toList());
jsonObject.put("children", buildKeys(newKey, jsonObject.getString("value")));
} else {
jsonObject.put("label", map.get(key).get(0));
jsonObject.put("value", StringUtils.isNotBlank(parentKey)?parentKey+":"+map.get(key).get(0):map.get(key).get(0));
}
jsonArray.add(jsonObject);
}
return jsonArray;
}
结果示例: