delver delver - 1 year ago 103
Java Question

Filter collection's elements

I have a

with list of

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) { = name;

public String getName() {
return name;


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

.filter(comment -> "comment1".equals(comment.getName())); //doesn't work

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

Answer Source
Optional<Topic> topic = getTopic();
if (topic.isPresent()) {
    List<Comment> comments = topic.get().getComments()
        .filter(comment -> "comment1".equals(comment.getName()))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download