Skip to content

Instantly share code, notes, and snippets.

@mombrea
Created July 15, 2014 14:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mombrea/876305ba611f16b7c10f to your computer and use it in GitHub Desktop.
Save mombrea/876305ba611f16b7c10f to your computer and use it in GitHub Desktop.
Threaded Comments
public static List<Comment> toThreadedComments(List<Comment> comments){
//comments should be sorted by date first
//The resulting array of threaded comments
List<Comment> threaded = new ArrayList<Comment>();
//An array used to hold processed comments which should be removed at the end of the cycle
List<Comment> removeComments = new ArrayList<Comment>();
//get the root comments first (comments with no parent)
for(int i = 0; i < comments.size(); i++){
Comment c = comments.get(i);
if(c.getComment_parent() == 0){
c.setCommentDepth(0); //A property of Comment to hold its depth
c.setChildCount(0); //A property of Comment to hold its child count
threaded.add(c);
removeComments.add(c);
}
}
if(removeComments.size() > 0){
//clear processed comments
comments.removeAll(removeComments);
removeComments.clear();
}
int depth = 0;
//get the child comments up to a max depth of 10
while(comments.size() > 0 && depth <= 10){
depth++;
for(int j = 0; j< comments.size(); j++){
Comment child = comments.get(j);
//check root comments for match
for(int i = 0; i < threaded.size(); i++){
Comment parent = threaded.get(i);
if(parent.getComment_id() == child.getComment_parent()){
parent.setChildCount(parent.getChildCount()+1);
child.setCommentDepth(depth+parent.getCommentDepth());
threaded.add(i+parent.getChildCount(),child);
removeComments.add(child);
continue;
}
}
}
if(removeComments.size() > 0){
//clear processed comments
comments.removeAll(removeComments);
removeComments.clear();
}
}
return threaded;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment