过滤集合的元素

时间:2016-11-10 13:51:27

标签: java java-8

我的Topic列表中包含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;
    }

}

我想调用getTopic,然后使用map从中获取评论并过滤列表条目,如下所示:

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

它没有用,因为在filter我有评论,而不是一条评论。如何在使用lambdas过滤器注释后收到新列表?

1 个答案:

答案 0 :(得分:5)

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