Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 过滤器收集';s元素_Java_Java 8 - Fatal编程技术网

Java 过滤器收集';s元素

Java 过滤器收集';s元素,java,java-8,Java,Java 8,我有一个主题和评论列表: 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

我有一个
主题
评论列表

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;
    }

}
它不起作用,因为在
filter
中我有注释,没有一条注释。如何在使用lambdas筛选注释后接收新列表?

可选主题=getTopic();
Optional<Topic> topic = getTopic();
if (topic.isPresent()) {
    List<Comment> comments = topic.get().getComments()
        .stream()
        .filter(comment -> "comment1".equals(comment.getName()))
        .collect(Collectors.toList());
}
if(topic.isPresent()){ List comments=topic.get().getComments() .stream() .filter(comment->“comment1”.equals(comment.getName())) .collect(Collectors.toList()); }
您不应该无条件地调用
Optional.get()
。通常,从方法返回一个
可选的
是有原因的。@Holger,改进了!我会使用
List result=getTopic().map(主题::getComments).orElse(Collections.emptyList()).stream().filter(comment->“comment1.equals(comment.getName())).collect(toList())getTopic().map(t->t.getComments().stream()).orElse(Collections.emptyList()).stream()
而不是
getTopic().map(t->t.getComments().stream()).orElseGet(stream::empty)
@Holger这应该是答案。
Optional<Topic> topic = getTopic();
if (topic.isPresent()) {
    List<Comment> comments = topic.get().getComments()
        .stream()
        .filter(comment -> "comment1".equals(comment.getName()))
        .collect(Collectors.toList());
}