比如省、市、县、区结构就是树形结构,主要解决思想是递归
public static List<Map> convertListToTree(List<Map> list, String parentColumn, String sonColumn) { List<Map> all = list.stream().filter(t -> !t.containsKey(sonColumn) || t.get(sonColumn) == null || StringUtils.isBlank(CommonUtils.objToString(t.get(sonColumn))) ).map((t) -> { t.put("children", getChildren(t, list, parentColumn, sonColumn)); return t; }).collect(Collectors.toList()); return all; } private static List<Map> getChildren(Map type, List<Map> all, String parentColumn, String sonColumn) { List<Map> children = all.stream().filter(t -> ((String) type.get(parentColumn)).equals((String) t.get(sonColumn)) ).map((t) -> { t.put("children", getChildren(t, all, parentColumn, sonColumn)); return t; }).collect(Collectors.toList()); return children; }
调用方式:
CommonUtils.convertListToTree(new ArrayList<>(cfxxList), "id", "parentId");