Vikash Kumar Singh
Vikash Kumar Singh

Reputation: 55

Count number of nested elements using stream api java

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

Upvotes: 4

Views: 118

Answers (2)

Mureinik
Mureinik

Reputation: 311188

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

Upvotes: 4

Vikas
Vikas

Reputation: 7165

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

Upvotes: 2

Related Questions