递归思想
把大问题转换为小问题(问题简单化),有明显的结束条件(不会无限循环)
递归例子
层级路径设置
@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);
}
}
}
分析
当我们要设置Recursion全路径时,就会发现,常用的遍历方法复杂而且未知条件层数,无从下手,这时我们运用递归的思想,把问题简单化。
其实就是:遍历设置路径;而递归的结束条件是没有子元素,找出这两个条件就可以很容易的实现递归逻辑。
网友评论