How can I check if all values in an array have a certain value?

拟墨画扇 提交于 2019-12-01 14:52:12

Or, if using java 8, you can do something like:

if(Arrays.stream(numbers).allMatch(x -> x == 2)) {
    // do something
}

Basically, pretty much everything that you might want to do that deals with collections/arrays, can be very concisely done with the Streams.

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

Using a function here will save you a lot of coding time and will also allow you to pass in arrays of arbitrary sizes (because you are iterating through the array according to its length).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!