最好是存在tree_path:存放着每一个节点的路径,查询通过这个字段就可以。倘若不存在,那就通过parent_id去递归查找父类。递归实现路径字段:@Data @NoArgsConstructor @AllArgsConstructor static class Recursion { private Integer id; private String path; private Integer parentId; } public static void main(String[] args) { List<Recursion> allList = Lists.newArrayList( new Recursion(3, "3", 2), new Recursion(1, "1", null), new Recursion(5, "5", null), new Recursion(2, "2", 1), new Recursion(4, "4", 3)); List<Recursion> rootList = allList.stream().filter(item -> Objects.isNull(item.getParentId())).collect(Collectors.toList()); recursionMethod(rootList, allList); // [{"id":3,"parentId":2,"path":"1,2,3"},{"id":1,"path":"1"},{"id":5,"path":"5"},{"id":2,"parentId":1,"path":"1,2"},{"id":4,"parentId":3,"path":"1,2,3,4"}] System.out.println(JSON.toJSONString(allList)); } private static void recursionMethod(List<Recursion> rootList, List<Recursion> allList) { for (Recursion root : rootList) { List<Recursion> childList = allList.stream().filter(item -> Objects.equals(root.getId(), item.getParentId())).collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(childList)) { childList.forEach(child -> child.setPath(root.getPath().concat(Constant.comma).concat(child.getPath()))); recursionMethod(childList, allList); } } }
最好是存在tree_path:存放着每一个节点的路径,查询通过这个字段就可以。
倘若不存在,那就通过parent_id去递归查找父类。
递归实现路径字段: