使用流API Java计算嵌套元素的数量

时间:2020-04-09 11:54:05

标签: java java-8 count java-stream

使用流计数内容的数量

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        h = {}
        for i, num in enumerate(nums):
            n = target - num
            if n not in h:
                h[num] = i
            else:
                return [h[n], i]

对于Java 8和Streams,我希望contentType等于视频的Content元素的数量。

要计算主题,我尝试了以下方法:

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

2 个答案:

答案 0 :(得分:4)

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

long videoContentCount = 
    subject.getUnits()
           .stream()
           .flatMap(u -> u.getTopics().stream())
           .flatMap(t -> t.getContents().stream())
           .filter(c -> c.getCountetType().equals("video"))
           .count();

答案 1 :(得分:2)

您使用以下流,

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