Stan Ostrovskii
Stan Ostrovskii

Reputation: 632

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

In Java, given an array of values (say integers), is there a way to efficiently check to see if they all have a certain value?

For example, with an array of integers such as:

int[] numbers = {2, 2, 2, 2, 2, 2, 2};

and you need to perform an action only if all of them are 2, is there a more effective way than doing this:

if (numbers[1] == 2 && numbers[2] == 2 && numbers[3] == 2 && …)

I know there are ways to do this in C++ but what about Java?

Upvotes: 0

Views: 3363

Answers (2)

Bhashit Parikh
Bhashit Parikh

Reputation: 3131

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.

Upvotes: 7

bha
bha

Reputation: 29

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).

Upvotes: 0

Related Questions