Java递归实现评论多级回复功能
吴振华 · 222浏览 · 发布于2022-06-27
这篇文章主要介绍了Java递归实现评论多级回复功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
最近工作需要做一个评论功能,除了展示评论之外,还需要展示评论回复,评论的回复的回复,这里就用到了递归实现评论的多级回复。
评论实体
数据库存储字段: id
评论id、parent_id
回复评论id、message
消息。其中如果评论不是回复评论,parent_id
为-1
。
创建一个评论实体 Comment
:
public class Comment { /** * id */ private Integer id; /** * 父类id */ private Integer parentId; /** * 消息 */ private String message; }
查询到所有的评论数据。方便展示树形数据,对Comment
添加回复列表
List<ViewComment> children
ViewComment
结构如下:
// 展示树形数据 public class ViewComment { /** * id */ private Integer id; /** * 父类id */ private Integer parentId; /** * 消息 */ private String message; /** * 回复列表 */ private List<ViewComment> children = new ArrayList<>(); }
添加非回复评论
非回复评论的parent_id
为-1
,先找到非回复评论:
List<ViewComment> viewCommentList = new ArrayList<>(); // 添加模拟数据 Comment comment1 = new Comment(1,-1,"留言1"); Comment comment2 = new Comment(2,-1,"留言2"); Comment comment3 = new Comment(3,1,"留言3,回复留言1"); Comment comment4 = new Comment(4,1,"留言4,回复留言1"); Comment comment5 = new Comment(5,2,"留言5,回复留言2"); Comment comment6 = new Comment(6,3,"留言6,回复留言3"); //添加非回复评论 for (Comment comment : commentList) { if (comment.getParentId() == -1) { ViewComment viewComment = new ViewComment(); BeanUtils.copyProperties(comment,viewComment); viewCommentList.add(viewComment); } }
递归添加回复评论
遍历每条非回复评论,递归添加回复评论:
for(ViewComment viewComment : viewCommentList) { add(viewComment,commentList); } private void add(ViewComment rootViewComment, List<Comment> commentList) { for (Comment comment : commentList) { // 找到匹配的 parentId if (rootViewComment.getId().equals(comment.getParentId())) { ViewComment viewComment = new ViewComment(); BeanUtils.copyProperties(comment,viewComment); rootViewComment.getChildren().add(viewComment); //递归调用 add(viewComment,commentList); } } }
遍历每条非回复评论。
非回复评论
id
匹配到评论的parentId
,添加到该评论的children
列表中。递归调用。
结果展示:
github 源码
相关推荐
PHP实现部分字符隐藏
沙雕mars · 1324浏览 · 2019-04-28 09:47:56
Java中ArrayList和LinkedList区别
kenrry1992 · 907浏览 · 2019-05-08 21:14:54
5月语言排行榜:R 跌出前二十,Python 紧咬 C++
manongba · 686浏览 · 2019-05-09 17:27:24
Tomcat 下载及安装配置
manongba · 968浏览 · 2019-05-13 21:03:56
什么是SpringBoot
iamitnan · 1086浏览 · 2019-05-14 22:20:36
分类专栏
最新发布
最热排行
0评论