This post will discuss how to check if all elements in an array are equal.

1. Using a Set

The idea here is to convert the array into a set and check the size of the set. If the size is 1, we can say that all elements in the array are equal. With Stream API, we can do something like this:

Download  Run Code

Output:

true

 
Here’s an equivalent version with Google’s Guava. The idea remains the same – convert the array into a set and check if the set size is equal to 1 or not.

Download Code

Output:

true

2. Using Stream.distinct() method

Alternatively, we can use Stream.distinct() to get the distinct elements of the stream and count the number of elements in the stream. If the count of elements is found to be 1, all elements in the array must be equal. The following program demonstrates it:

Download  Run Code

Output:

true

3. Using Stream.allMatch() method

Finally, we can check if all elements of the array match the first element of the array. Here’s another Java 8 one-liner demonstrating this using the allMatch() method:

Download  Run Code

Output:

true

 
Here’s a version that works with Java 7 or less:

Download  Run Code

Output:

true

That’s all about checking if all elements in an array are equal.