我有一个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;
}
}
Run Code Online (Sandbox Code Playgroud)
我想调用getTopic,然后从中获取注释map并过滤列表中的条目,如下所示:
getTopic()
.map(Topic::getComments)
.filter(comment -> "comment1".equals(comment.getName())); //doesn't work
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为filter我有评论,没有一条评论.使用lambdas过滤器注释后如何收到新列表?
Optional<Topic> topic = getTopic();
if (topic.isPresent()) {
List<Comment> comments = topic.get().getComments()
.stream()
.filter(comment -> "comment1".equals(comment.getName()))
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
65 次 |
| 最近记录: |