关于java:Java递归实现评论多级回复

5次阅读

共计 1641 个字符,预计需要花费 5 分钟才能阅读完成。

最近工作须要做一个评论性能,除了展现评论之外,还须要展现评论回复,评论的回复的回复,这里就用到了 递归 实现评论的 多级回复

评论实体

数据库存储字段: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 源码

https://github.com/jeremylai7/java-codes/tree/master/basis/src/main/java/recurve

正文完
 0