【问题标题】:Simplification of if statement with an array in javajava中带有数组的if语句的简化
【发布时间】:2017-03-17 23:36:33
【问题描述】:

我有一个如下所示的 if 语句,我正在检查 count 数组中的所有值是否都为零。

if (count[1] == 0 && count[2] == 0 && count[3] == 0 && count[4] == 0 
&& count[5] == 0 && count[6] == 0) {

}

有没有办法简化这个语句?另外请注意,我不想检查count[0]

【问题讨论】:

  • 您可以使用循环(在您的情况下从 1 开始)设置布尔结果变量。

标签: java arrays if-statement


【解决方案1】:

您可以使用IntStreamallMatch(IntPredicate)

if (IntStream.of(count).allMatch(x -> x == 0)) {
    // ...
}

这将包括count[0],排除count[0],您可以改为这样做

if (IntStream.rangeOf(1, count.length).allMatch(x -> count[x] == 0)) {

}

或者(感谢@Louis Wasserman

if (IntStream.of(count).skip(1).allMatch(x -> x == 0)) {
    // ...
}

【讨论】:

  • 我倾向于写更短的IntStream.of(count).skip(1).allMatch(x -> x == 0)
【解决方案2】:

在 Java 8 中

 boolean  isAllZero = Arrays.asList(myArray).stream().allMatch(val -> val == 0);

【讨论】:

    【解决方案3】:

    一种可能的解决方案是使用简单的 for 循环遍历 count 数组并检查数组中包含的元素的值,以确定它们的值是否为零。

    public boolean isAllZero(int[] array){
       for(int i = 1; i < array.length; i++){
          if(array[i] != 0){
             return false;
          }
       } 
       return true;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-12
      • 1970-01-01
      • 2017-04-11
      相关资源
      最近更新 更多