/**
* 获取子级
*
* @param fieldParentId 父级ID字段
* @param fieldCurId 当前ID字段
* @param data 集合数据
* @param curId 当前ID值
* @return children 集合
*/
private static List<Map<String, Object>> getChildren(String fieldParentId, String fieldCurId,
List<Map<String, Object>> data, String curId) {
/**
* 1.对数据校验处理
*/
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
if (data == null || data.size() == 0) {
return list;
}
/**
* 2.遍历匹配父子级关系数据
*/
for (Map<String, Object> dataMap : data) {
if (curId.equals(dataMap.get(fieldParentId).toString())) {
dataMap.put("children",
getChildren(fieldParentId, fieldCurId, data, dataMap.get(fieldCurId).toString()));
list.add(dataMap);
}
}
/**
* 3.返回处理后的结果对象
*/
return list;
}
测试方法(调用示例):?
public static void main(String[] args) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
list.add(new HashMap<String, Object>() {
{
put("parent_id", "-1");
put("id", "1");
put("name", "省1");
}
});
list.add(new HashMap<String, Object>() {
{
put("parent_id", "-1");
put("id", "2");
put("name", "省2");
}
});
list.add(new HashMap<String, Object>() {
{
put("parent_id", "2");
put("id", "22");
put("name", "省2市2");
}
});
for (Map<String, Object> map : list) {
map.put("children", getChildren("parent_id", "id", list, map.get("id").toString()));
}
for (Map<String, Object> map : list) {
System.out.println(map);
}
}
输出结果:
?
|