Java遞歸實現(xiàn)評論多級回復(fù)功能
最近工作需要做一個評論功能,除了展示評論之外,還需要展示評論回復(fù),評論的回復(fù)的回復(fù),這里就用到了遞歸實現(xiàn)評論的多級回復(fù)。
評論實體
數(shù)據(jù)庫存儲字段: id 評論id、parent_id 回復(fù)評論id、message 消息。其中如果評論不是回復(fù)評論,parent_id 為-1。
創(chuàng)建一個評論實體 Comment:
public class Comment {
/**
* id
*/
private Integer id;
/**
* 父類id
*/
private Integer parentId;
/**
* 消息
*/
private String message;
}查詢到所有的評論數(shù)據(jù)。方便展示樹形數(shù)據(jù),對Comment添加回復(fù)列表
List<ViewComment> children
ViewComment結(jié)構(gòu)如下:
// 展示樹形數(shù)據(jù)
public class ViewComment {
/**
* id
*/
private Integer id;
/**
* 父類id
*/
private Integer parentId;
/**
* 消息
*/
private String message;
/**
* 回復(fù)列表
*/
private List<ViewComment> children = new ArrayList<>();
}
添加非回復(fù)評論
非回復(fù)評論的parent_id為-1,先找到非回復(fù)評論:
List<ViewComment> viewCommentList = new ArrayList<>();
// 添加模擬數(shù)據(jù)
Comment comment1 = new Comment(1,-1,"留言1");
Comment comment2 = new Comment(2,-1,"留言2");
Comment comment3 = new Comment(3,1,"留言3,回復(fù)留言1");
Comment comment4 = new Comment(4,1,"留言4,回復(fù)留言1");
Comment comment5 = new Comment(5,2,"留言5,回復(fù)留言2");
Comment comment6 = new Comment(6,3,"留言6,回復(fù)留言3");
//添加非回復(fù)評論
for (Comment comment : commentList) {
if (comment.getParentId() == -1) {
ViewComment viewComment = new ViewComment();
BeanUtils.copyProperties(comment,viewComment);
viewCommentList.add(viewComment);
}
}遞歸添加回復(fù)評論
遍歷每條非回復(fù)評論,遞歸添加回復(fù)評論:
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);
//遞歸調(diào)用
add(viewComment,commentList);
}
}
}- 遍歷每條非回復(fù)評論。
- 非回復(fù)評論
id匹配到評論的parentId,添加到該評論的children列表中。 - 遞歸調(diào)用。
結(jié)果展示:

github 源碼
https://github.com/jeremylai7/java-codes/tree/master/basis/src/main/java/recurve
到此這篇關(guān)于Java遞歸實現(xiàn)評論多級回復(fù)的文章就介紹到這了,更多相關(guān)Java評論多級回復(fù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot整合Mybatis-plus實現(xiàn)多級評論功能
本文介紹了如何使用SpringBoot整合Mybatis-plus實現(xiàn)多級評論功能,同時提供了數(shù)據(jù)庫的設(shè)計和詳細的后端代碼,前端界面使用的Vue2,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-05-05
Mybatis?連接mysql數(shù)據(jù)庫底層運行的原理分析
這篇文章主要介紹了Mybatis?連接mysql數(shù)據(jù)庫底層運行的原理分析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
詳解Java中的線程讓步y(tǒng)ield()與線程休眠sleep()方法
Java中的線程讓步會讓線程讓出優(yōu)先級,而休眠則會讓線程進入阻塞狀態(tài)等待被喚醒,這里我們對比線程等待的wait()方法,來詳解Java中的線程讓步y(tǒng)ield()與線程休眠sleep()方法2016-07-07
JavaEE實現(xiàn)基于SMTP協(xié)議的郵件發(fā)送功能
這篇文章主要為大家詳細介紹了JavaEE實現(xiàn)基于SMTP協(xié)議的郵件發(fā)送功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-05-05

