Java——list转树形结构

作者专注于Java、架构、Linux、小程序、爬虫、自动化等技术。 工作期间含泪整理出一些资料,微信搜索【javaUp】,回复 【java】【黑客】【爬虫】【小程序】【面试】等关键字免费获取资料。技术交流、项目合作可私聊。 微信:shuhao-99999 

比如省、市、县、区结构就是树形结构,主要解决思想是递归

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;
}

原文地址:https://www.cnblogs.com/shuhao66666/p/15196339.html