我需要检查列表中是否至少有 1 项具有 X、Y 和 Z(并非同时全部)。例如项目 1 有 x,项目 2 有 y 和 z。
我认为最好不要创建多个循环并仅检查其中一个循环,而是存储一个变量然后检查它,这样一旦为 true 就不能再次将其设置为 false。
似乎我可能缺少一种更好的方法来做到这一点,那么有吗?
谢谢
boolean hasX = false;
boolean hasY = false;
boolean hasZ = false;
for (ItemType item : Items) {
if (!hasX) { hasX = DoesHaveX(item); }
if (!hasY) { hasY = DoesHaveY(item); }
if (!hasZ) { hasZ = DoesHaveZ(item); }
}
最佳答案
如果您打算坚持使用 1.8 以下的 JVM,那么您的代码就可以了!
也许您可以跳过一些操作,例如在找到三个 boolean 值的匹配项后中断循环,并仅检查那些尚未找到的操作。
for (ItemType item : items) {
hasX = hasX || doesHaveX(item);
hasY = hasY || doesHaveY(item);
hasZ = hasZ || doesHaveZ(item);
if (hasX && hasY && hasZ) {
break;
}
}
如果您可以使用流,那么最好在创建每个变量时对其进行初始化,如下所示:
boolean hasX = items.stream().anyMatch(this::doesHaveX); // goes trough the elements until a match is found.
boolean hasY = items.stream().anyMatch(this::doesHaveY); // goes trough the elements until a match is found.
boolean hasZ = items.stream().anyMatch(this::doesHaveZ); // goes trough the elements until a match is found.
关于java - 有没有更好的方法来编写这个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56902308/