【问题标题】:Simplify counting with two for loops (using stream)使用两个 for 循环简化计数(使用流)
【发布时间】:2019-03-14 00:46:02
【问题描述】:

我有这段代码,我想使用流来编写它。 我需要检查 hList 是否包含所有 dFoods 元素。

int count = 0;
for(int i = 0; i< dFoods.size(); i++){
    for(int j = 0; j< hList.size(); j++){
        if(hList.get(j).title.equals(dFoods.get(i).name) && hList.get(j).time.equals(dFoods.get(i).timestamp)){
            count ++;
        }
    }
}
if(count != dFoods.Elements.size()){
    System.out.println("Not all dFoods elements are in a hList");
}

我试过了

dFoods.forEach(df -> {
        hList.stream().filter(hl -> df.Name.equals(hl.title) && df.Timestamp.equals(hl.time)).forEach(hl -> {
            System.out.println(df.Name + " " + df.Timestamp);
        });
    });

而且它写得正确,但我需要数数,但不能这样算。

【问题讨论】:

    标签: java for-loop java-8 java-stream


    【解决方案1】:
    dFoods.stream()
      .allMatch(df -> 
          hList.stream
            .anyMatch(hl -> df.Name.equals(hl.title) && df.Timestamp.equals(hl.time)))
    

    【讨论】:

      【解决方案2】:
      dFoods.forEach(df -> {
              hList.stream().filter(hl -> df.Name.equals(hl.title) && df.Timestamp.equals(hl.time)).count();
          });
      

      干杯!

      【讨论】:

        【解决方案3】:

        首先找到dFoodshList 之间的相似度计数。

        Long countOfMatching = dFoods.stream()
                .filter(df ->
                        hList.stream()
                                .anyMatch(hl -> df.Name.equals(hl.title) && df.Timestamp.equals(hl.time)))
                .count();
        

        如果 dFood 的元素在 hList 中,则内部流返回 true。如果将true 返回到外部流进行收集,则进行过滤。现在您可以获得两个列表之间的相似度计数。如果两个列表的列表大小与此找到的值匹配,则现在应用。如果您只想要 if all contains 作为布尔结果,请这样做;

        Boolean allMatched = dFoods.stream()
                .allMatch(df ->
                        hList.stream()
                                .anyMatch(hl -> df.Name.equals(hl.title) && df.Timestamp.equals(hl.time)));
        

        【讨论】:

          【解决方案4】:

          如果足够的话,greg 提供布尔状态的解决方案似乎是最好的。

          int count = (int) dFoods.stream()
              .mapToLong(
                  f -> hList.stream()
                      .filter(h -> h.title.equals(f.name) && h.time.equals(f.timestamp))
                      .count())
              .sum();
          

          其中hList 必须是隐式final。

          【讨论】:

            猜你喜欢
            • 2010-11-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-30
            • 2017-12-28
            • 2020-01-25
            相关资源
            最近更新 更多