是否可以通过这种方式检查二维数组中的所有元素是否相同?

Is it possible to check this way, that all elements in 2d Array are the same?

所以我用谷歌搜索了这个问题。只有这个来自 StackOF 的 link 出现了。

我觉得我的解决方案很简单,但是没有人写过,这有意义吗?

代码如下:

public boolean areAllTheSame(int[][] image) {

    // Create a new set, so we can store our unique elems there.
    Set<Integer> set = new HashSet<>();

    //Iterate through all elements, add to our HashSet set
    for (int[] ints : image) {
        for (int anInt : ints) {
            set.add(anInt);
        }
    }
    // Because set has only unique elements, if all are the same => size should be 1

    return set.size() == 1;
} // end of areAllTheSame

看起来效率很低,如果你想检查一个多维数组是否只包含一个元素你可以只取第一个元素然后将它与所有其他数字进行比较,如果一个与你不匹配return假

我认为有更多方法,其中之一是使用 java 流式传输 :

public boolean areAllTheSame(int[][] image) {
    return Arrays.stream(image)
            .flatMapToInt(Arrays::stream)
            .distinct()
            .count() == 1;
}

怎么样:

public boolean areAllTheSame(int[][] image) {
  // assuming `image` >= 1x1 pixels

  int expectedPixel = image[0][0];

  for (int[] pixels: image)
    for (int pixel: pixels)
      if(pixel != expectedPixel)
        return false;

  return true;
}

知道数组不均匀就停止循环,不需要分配HashSet<Integer>.