英文:
Count number of nested elements using stream api java
问题
统计使用流(Stream)的内容数量
class Subject {
private String id;
private String name;
private List<Unit> units;
}
class Unit {
private String id;
private String name;
private List<Topic> topics;
}
class Topic {
private String id;
private String name;
private List<Content> contents;
}
class Content {
private String id;
private String contentType;
private SubTopic subtopic;
}
使用Java 8和Streams,我想要统计contentType为video的Content元素的数量。
要统计topic数量,我尝试了以下代码:
```java
int topicCount = subject.getUnits().stream()
.map(Unit::getTopics)
.filter(topics -> topics != null)
.mapToInt(List::size)
.sum();
英文:
Count number of content using stream
class Subject {
private String id;
private String name;
private List<Unit> units;
}
class Unit {
private String id;
private String name;
private List<Topic> topics;
}
class Topic {
private String id;
private String name;
private List<Content> contents;
}
class Content {
private String id;
private String contentType;
private SubTopic subtopic;
}
With Java 8 and Streams I want the count of the Content elements which is of contentType equal to the video.
To count topic I tried this:
int topicCount = subject.getUnits().stream()
.map(Unit::getTopics)
.filter(topics -> topics != null)
.mapToInt(List::size)
.sum();
答案1
得分: 4
你可以对嵌套的元素进行扁平映射并进行计数:
long videoContentCount =
subject.getUnits()
.stream()
.flatMap(u -> u.getTopics().stream())
.flatMap(t -> t.getContents().stream())
.filter(c -> c.getCountetType().equals("video"))
.count();
英文:
You could flat map the nested elements and count them:
long videoContentCount =
subject.getUnits()
.stream()
.flatMap(u -> u.getTopics().stream())
.flatMap(t -> t.getContents().stream())
.filter(c -> c.getCountetType().equals("video"))
.count();
答案2
得分: 2
您可以按如下方式使用流:
subject.getUnits()
.stream()
.map(Unit::getTopics)
.flatMap(List::stream)
.map(Topic::getContents)
.flatMap(List::stream)
.map(Content::getContentType)
.filter("video"::equals)
.count();
您也可以避免使用 map,像这样:
subject.getUnits()
.stream()
.flatMap(e->e.getTopics().stream())
.flatMap(e->e.getContents().stream())
.map(Content::getContentType)
.filter("video"::equals)
.count();
英文:
You use streams as below,
subject.getUnits()
.stream()
.map(Unit::getTopics)
.flatMap(List::stream)
.map(Topic::getContents)
.flatMap(List::stream)
.map(Content::getContentType)
.filter("video"::equals)
.count();
You can avoid map,
subject.getUnits()
.stream()
.flatMap(e->e.getTopics().stream())
.flatMap(e->e.getContents().stream())
.map(Content::getContentType)
.filter("video"::equals)
.count();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论