本篇文章小编给大家分享一下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结构如下:
// 展示树形数据 public class ViewComment { /** * id */ private Integer id; /** * 父类id */ private Integer parentId; /** * 消息 */ private String message; /** * 回复列表 */ private Listchildren = new ArrayList<>(); }
添加非回复评论
非回复评论的parent_id为-1,先找到非回复评论:
ListviewCommentList = 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, ListcommentList) { 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列表中。
递归调用。
结果展示:
敢达决战官方正版 安卓版v6.7.9
下载敢达决战 安卓版v6.7.9
下载像素火影骨架佐助 (Perseverance Fire Shadow)手机版v1.16
下载要塞英雄 安卓版v33.20.0-39082670-Android
下载梦想城镇vivo最新版本 安卓版v12.0.1
梦想城镇vivo版是这款卡通风模拟经营类手游的渠道服版本,玩
怦然心动的瞬间 安卓版v1.0
怦然心动的瞬间是一款真人向的恋爱互动游戏,在游戏中玩家将扮演
曼尼汉堡店游戏 安卓版v1.0.3
曼尼汉堡店是一款非常好玩的精品恐怖类型冒险游戏,在这款游戏中
现代总统模拟器去广告版 安卓版v1.0.46
现代总统模拟器是一款休闲养成类游戏,可能对于不少的玩家来说都
现代总统模拟器付费完整版 安卓版v1.0.46
现代总统模拟器高级版在商店是需要付费的,相对于普通版本,高级