java 实现评论多层楼层合并为二层楼层(父级评论的子级及其嵌套子级)

论坛实现类似b站评论楼层
在这里插入图片描述
思路:
1.先用递归的方式将所有数据查出
2.再用递归的方式将父级评论的子级及其嵌套子级

上代码:
1.递归查询所有评论
实体类 自己写吧

 public void recursiveCommonReplyList(List<CourseCommentDto> courseCommonList){
		for(CourseCommentDto cd :courseCommonList){
			List<CourseCommentDto> courseCommonReplyList = findCourseCommonReplyList(cd.getId());
			if(courseCommonReplyList !=null){
				cd.setReplyList(courseCommonReplyList);
				recursiveCommonReplyList(courseCommonReplyList);
			}
		}
	}

2.再用递归的方式将父级评论的子级及其嵌套子级

public void mergeChildrenList(List<CourseCommentDto> courseCommonList){
		for (CourseCommentDto comment : courseCommonList) {
			// 防止checkForComodification(),而建立一个新集合
			ArrayList<CourseCommentDto> fatherChildren = new ArrayList<>();
			// 递归处理子级的回复,即回复内有回复
			findChildren(comment, fatherChildren);
			// 将递归处理后的集合放回父级的孩子中
			comment.setReplyList(fatherChildren);
		}
	}


	/**
	 * 二层回复  父级评论的子级及其嵌套子级
	 * **/
	public void findChildren(CourseCommentDto  parent, List<CourseCommentDto> fatherChildren) {
		// 找出直接子级
		List<CourseCommentDto> comments = parent.getReplyList();
		// 遍历直接子级的子级
		for (CourseCommentDto comment : comments) {
			// 若非空,则还有子级,递归
			if (!comment.getReplyList().isEmpty()) {
				findChildren(comment, fatherChildren);
			}
			// 已经到了最底层的嵌套关系,将该回复放入新建立的集合
			fatherChildren.add(comment);
			// 容易忽略的地方:将相对底层的子级放入新建立的集合之后
			// 则表示解除了嵌套关系,对应的其父级的子级应该设为空
			comment.setReplyList(new ArrayList<>());
		}
	}

缺点:当回复条数太多时 由于子类是由子级嵌套实现 所以无法在mysql层进行分页 分页方法需要重新编写

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值