过滤集合的元素

Fee*_*eco 3 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;
    }

}
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过滤器注释后如何收到新列表?

Mor*_*van 5

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)

  • 我使用`List <Comment> result = getTopic().map(Topic :: getComments).orElse(Collections.emptyList()).stream().filter(comment - >"comment1".equals(comment.getName) ())).collect(toList());` (6认同)
  • 而不是`getTopic().map(Topic :: getComments).orElse(Collections.emptyList()).stream()`你也可以使用`getTopic().map(t - > t.getComments().stream( )).orElseGet(Stream :: empty)` (5认同)
  • 你不应该无条件地调用`Optional.get()`.通常,有一个原因可以从方法返回`Optional`. (3认同)
  • @Holger这应该是一个答案. (3认同)