栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

论坛实现类似b站评论楼层

思路:
1.先用递归的方式将所有数据查出
2.再用递归的方式将父级评论的子级及其嵌套子级

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

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

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

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


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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/340778.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号