Say I have 2 nested collections, kind of a collection of multiple OneToMany relations.
For example a Post
has many Comments
, a Comment
can have many Tags
, sets. So let's just limit to the Post and Comments relation defined as follows as POJOs:
@Getter
@Setter
private static class Post {
private String title;
private Set < Comment > comments = new HashSet < > ();
public Post(String title) {
this.title = title;
}
public Post addComment(Comment comment) {
getComments().add(comment);
return this;
}
}
@Getter
@Setter
private static class Comment {
private String text;
public Comment(String text) {
this.text = text;
}
}
Let's create 2 Posts with comments:
Post post1 = new Post("post-1").
addComment(new Comment("com-1")).
addComment(new Comment("com-2"));
Post post2 = new Post("post-2").
addComment(new Comment("com-21")).
addComment(new Comment("com-22")).
addComment(new Comment("com-1")).
addComment(new Comment("com-2"));
The question is how to find a collection of comments for the above posts having the same text
value?
I tried to use retainAll
but it fails to solve that:
Set <Comment> post1Comments = new HashSet(post1.getComments());
System.out.println("post1 comments before: " + post1Comments);
post1Comments.retainAll(post2.getComments());
System.out.println("post1 comments after: " + post1Comments);
Any ideas?