1 回答

TA貢獻1829條經驗 獲得超7個贊
我認為您需要遍歷結果列表,當您找到具有父評論的結果時,您進入地圖,獲取父評論,將其計數加一并將其粘貼回地圖中:
假設您的 Result 類是這樣的:
class Result {
private String id;
private String parentCommentID;
public Result(String id, String parentCommentID) {
this.id = id;
this.parentCommentID = parentCommentID;
}
// GETTERS/SETTERS
}
你有一個包含 3 個結果的討論列表
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}
添加回答
舉報