list转换成树形结构
开发中常常遇到查出来是list,但需要转换成树形结构,特别是遇到省、市、县、区或者部门角色查询等,这时候可以在sql语句中处理,也可以在代码中转换,先将代码中处理方式贴出来
public static List<Map> convertToTree(List<Map> list) {
List<Map> all = list.stream().filter(t ->
!t.containsKey("parentId") || t.get("parentId") == null || "".equals(t.get("parentId").toString())
).map((t) -> {
t.put("children", getChildren(t, list));
return t;
}).collect(Collectors.toList());
return all;
}
private static List<Map> getChildren(Map type, List<Map> all) {
List<Map> children = all.stream().filter(t ->
((String)type.get("id")).equals((String)t.get("parentId"))
).map((t) -> {
t.put("children", getChildren(t, all));
return t;
}).collect(Collectors.toList());
return children;
}