首页 > 解决方案 > 使用两个 for 循环简化计数(使用流)

问题描述

我有这段代码,我想使用流来编写它。我需要检查 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);
        });
    });

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

标签: javafor-loopjava-8java-stream

解决方案


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

推荐阅读