Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter collection's elements

Tags:

java

java-8

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?

like image 690
Feeco Avatar asked Jul 24 '26 04:07

Feeco


1 Answers

Optional<Topic> topic = getTopic();
if (topic.isPresent()) {
    List<Comment> comments = topic.get().getComments()
        .stream()
        .filter(comment -> "comment1".equals(comment.getName()))
        .collect(Collectors.toList());
}
like image 88
cringineer Avatar answered Jul 26 '26 19:07

cringineer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!