delver delver - 23 days ago 13
Java Question

Filter collection's elements

I have a

Topic
with list of
Comment
:

public Optional<Topic> getTopic() {
return Optional.ofNullable(new Topic(Collections.singletonList(new Comment("comment1"))));
}

public class Topic {

private List<Comment> comments;

public Topic(List<Comment> comments) {
this.comments = comments;
}

public List<Comment> getComments() {
return comments;
}

}

public class Comment {

private String name;

public Comment(String name) {
this.name = name;
}

public String getName() {
return name;
}

}


I want to call
getTopic
, then fetch comments from it with
map
and filter entries of the list like this:

getTopic()
.map(Topic::getComments)
.filter(comment -> "comment1".equals(comment.getName())); //doesn't work


It doesn't work, because in
filter
I have comments, not a single comment. How can I receive new list after filter comments with lambdas?

Answer
Optional<Topic> topic = getTopic();
if (topic.isPresent()) {
    List<Comment> comments = topic.get().getComments()
        .stream()
        .filter(comment -> "comment1".equals(comment.getName()))
        .collect(Collectors.toList());
}
Comments