Search This Blog

Tuesday, November 8, 2016

How to fetch from list of nested list- Dynamic Loop

Assume the bean is like below, CommentsBean has CommentsBeanlist.

public class CommentsBean {

int id;
int parentId;
String msg;
List commentsBeanList;

public CommentsBean() {

}

public CommentsBean(int id, int parentId, String msg) {
super();
this.id = id;
this.parentId = parentId;
this.msg = msg;
}

@Override
public String toString() {
return "CommentsBean [id=" + id + ", parentId=" + parentId + ", msg=" + msg + ", commentsBeanList="
+ commentsBeanList + "]";
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public int getParentId() {
return parentId;
}

public void setParentId(int parentId) {
this.parentId = parentId;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public List getCommentsBeanList() {
return commentsBeanList;
}

public void setCommentsBeanList(List commentsBeanList) {
this.commentsBeanList = commentsBeanList;
}


}


Program to extract that dynamically.

public class DynamicListLoop {

public static void main(String[] args) {
List commntsBeanList = new ArrayList<>();
List commntsBeanChildList1 = new ArrayList<>();
List commntsBeanChildList11 = new ArrayList<>();
CommentsBean commentsBeanchild20 = new CommentsBean(4,-1, "second");
CommentsBean commentsBeanchild21 = new CommentsBean(5,4, "second-child-1");
commntsBeanChildList11.add(commentsBeanchild20);
commntsBeanChildList11.add(commentsBeanchild21);
CommentsBean commentsBeanchild2 = new CommentsBean(3,2, "first-child-2");
CommentsBean commentsBeanchild = new CommentsBean(2,1, "first-child-1");
commentsBeanchild.setCommentsBeanList(commntsBeanChildList11);
commntsBeanChildList1.add(commentsBeanchild);
commntsBeanChildList1.add(commentsBeanchild2);
CommentsBean commentsBean = new CommentsBean(1,-1, "first");
commentsBean.setCommentsBeanList(commntsBeanChildList1);
commntsBeanList.add(commentsBean);
System.out.println(commntsBeanList.toString());
//write a function and pass the parent bean list.
commentsBeanParseInLoop (commntsBeanList );

}
public static void commentsBeanParseInLoop ( List commntsBeanList )
{
if ( commntsBeanList!=null && commntsBeanList.size() > 0 )
{
for ( CommentsBean cb : commntsBeanList )
{
System.out.println(cb.getId() + " : " + cb.getMsg() );
if ( cb.getCommentsBeanList() !=null && cb.getCommentsBeanList().size() > 0 )
{
//call the same function and pass the inner bean list
commentsBeanParseInLoop ( cb.getCommentsBeanList() );
}
}
}
}

}

Hit Counter


View My Stats