I have a Topic with list of 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;
}
}
I want to call getTopic, then fetch comments from it with map and filter entries of the list like this:
getTopic()
.map(Topic::getComments)
.filter(comment -> "comment1".equals(comment.getName())); //doesn't work
It doesn't work, because in filter I have comments, not a single comment. How can I receive new list after filter comments with lambdas?
Optional<Topic> topic = getTopic();
if (topic.isPresent()) {
List<Comment> comments = topic.get().getComments()
.stream()
.filter(comment -> "comment1".equals(comment.getName()))
.collect(Collectors.toList());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With