1 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
我認(rèn)為您需要遍歷結(jié)果列表,當(dāng)您找到具有父評論的結(jié)果時(shí),您進(jìn)入地圖,獲取父評論,將其計(jì)數(shù)加一并將其粘貼回地圖中:
假設(shè)您的 Result 類是這樣的:
class Result {
private String id;
private String parentCommentID;
public Result(String id, String parentCommentID) {
this.id = id;
this.parentCommentID = parentCommentID;
}
// GETTERS/SETTERS
}
你有一個(gè)包含 3 個(gè)結(jié)果的討論列表
discussionsList = Arrays.asList(
new Result("1439", null),
new Result("1500", "1439"),
new Result("1801", "1439")
);
像你的情況一樣, 1439 沒有父母, 1500 和 1501 都有 1439 作為父母
然后你可以做這樣的事情:
Map<String, Integer> commentsCountMap = new HashMap<>();
// Loop through the discussion Map
for(Result res : discussionsList) {
String parentCommentId = res.getParentCommentID();
// If the Result has a parent comment
if(parentCommentId != null) {
// get the count for this parent comment (default to 0)
int nbCommentsForParent = commentsCountMap.getOrDefault(parentCommentId, 0);
// increment the count
nbCommentsForParent++;
// Update the Map with the new count
commentsCountMap.put(parentCommentId, nbCommentsForParent);
}
}
System.out.println(commentsCountMap);
這輸出
{1439=2}
添加回答
舉報(bào)