使用流api java计算嵌套元素的数量

使用流api java计算嵌套元素的数量,java,java-8,count,java-stream,Java,Java 8,Count,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 S

使用流计算内容的数量

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

您可以平面映射嵌套元素并对其进行计数:

long videoContentCount=
subject.getUnits()
.stream()
.flatMap(u->u.getTopics().stream())
.flatMap(t->t.getContents().stream())
.filter(c->c.getCounteType().equals(“视频”))
.count();

您使用的流如下所示

subject.getUnits()
        .stream()
        .map(Unit::getTopics)
        .flatMap(List::stream)
        .map(Topic::getContents)
        .flatMap(List::stream)
        .map(Content::getContentType)
        .filter("video"::equals)
        .count();
你可以避开地图

subject.getUnits()
        .stream()
        .flatMap(e->e.getTopics().stream())
        .flatMap(e->e.getContents().stream())
        .map(Content::getContentType)
        .filter("video"::equals)
        .count();

flatMap(Unit::getTopics)
,这不需要
getTopics
返回
流吗?@Naman arg,是的,我忘了流,谢谢注意!已编辑并修复。正在为此添加额外点。您可以对内容类型使用
enum
,而不是字符串文本,以实现更好的类型安全性,从而避免
getContentType
的NPE。您真的愿意检查
列表是否为
null
?当您编写
.filter(主题->主题!=null)
时?我的意思是我可以看,但你应该避免。(将
null
分配给
列表
subject.getUnits()
        .stream()
        .flatMap(e->e.getTopics().stream())
        .flatMap(e->e.getContents().stream())
        .map(Content::getContentType)
        .filter("video"::equals)
        .count();