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