我的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过滤器注释后收到新列表?
答案 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());
}