1. Overview

When working with arrays in Java, there are situations where we need to verify if all elements in an array are equal.

In this tutorial, we’ll explore how to check if all elements in an array are equal in Java.

2. Introduction to the Problem

Checking if all elements in an array are equal sounds straightforward. However, there are some edge cases we need to consider, such as when the array is null or empty, when it only contains one element, when it contains null values, and so on.

Furthermore, in Java, we have object arrays and primitive arrays.

In this tutorial, we’ll cover these scenarios.

Let’s first look at how to check all elements are equal for an object array.

3. Object Arrays

First, let’s list some example arrays whose elements are equal or not:

// all-equal = true arrays:
final static String[] ARRAY_ALL_EQ = { "java", "java", "java", "java" };
final static String[] ARRAY_ALL_NULL = { null, null, null, null };
final static String[] ARRAY_SINGLE_EL = { "java" };
  
// all-equal = false arrays:
final static String[] ARRAY_NOT_EQ = { "java", "kotlin", "java", "java" };
final static String[] ARRAY_EMPTY = {};
final static String[] ARRAY_NULL = null;

As the examples show, if an array contains only one element, we consider all elements equal. However, if an array is null or empty, it contains no elements. Naturally, its elements are not equal.

Next, let’s take these arrays as our inputs to create different methods to perform the check.

3.1. A Loop-Based Generic Method

A straightforward idea is to check each element in the given array in a loop. To make the solution accept all object arrays, we can a generic method:

<T> boolean isAllEqual(T[] array) {
    if (array == null || array.length == 0) {
        return false;
    }
    for (int i = 1; i < array.length; i++) {
        if (!Objects.equals(array[0], array[i])) {
            return false;
        }
    }
    return true;
}

In the isAllEqual() method, we first examine whether the array is empty or null and return the expected result (false). Then, the method **checks if all elements in the array are equal by comparing each element to the first element (array[0])**. If any element differs, the method returns false; otherwise, it returns true.

It’s worth mentioning that when we compare element values, we use Objects.equals() instead of equals(). This is because *the Objects.equals() static method can safely handle null values and won’t raise NullPointerExceptions*.

Next, let’s test the method with our array inputs:

assertTrue(isAllEqual(ARRAY_ALL_EQ));
assertTrue(isAllEqual(ARRAY_ALL_NULL));
assertTrue(isAllEqual(ARRAY_SINGLE_EL));
 
assertFalse(isAllEqual(ARRAY_NOT_EQ));
assertFalse(isAllEqual(ARRAY_EMPTY));
assertFalse(isAllEqual(ARRAY_NULL));

The test passes if we give it a run. So, our isAllEqual() solves the problem.

3.2. Using Stream‘s distinct() or allMatch()

Java 1.8 has introduced a significant feature: Stream API. We can use Arrays.stream(array) to convert an array to a Stream, and then use Stream‘s handy methods to manipulate the elements.

Next, we’ll solve the problem using Stream‘s distinct() and allMatch() methods.

distinct() can remove duplicate elements from a Stream. Therefore, we’ll have only one element after distinct() if all elements are equal:

<T> boolean isAllEqualByDistinct(T[] array) {
    // ... null and empty array handling
    return Arrays.stream(array)
      .distinct()
      .count() == 1;
}

As the example shows, the implementation is pretty compact. The following test shows the distinct() approach does the job:

assertTrue(isAllEqualByDistinct(ARRAY_ALL_EQ));
assertTrue(isAllEqualByDistinct(ARRAY_ALL_NULL));
assertTrue(isAllEqualByDistinct(ARRAY_SINGLE_EL));
 
assertFalse(isAllEqualByDistinct(ARRAY_NOT_EQ));
assertFalse(isAllEqualByDistinct(ARRAY_EMPTY));
assertFalse(isAllEqualByDistinct(ARRAY_NULL));

Alternatively, we can also use allMatch() to solve the problem. The allMatch() method checks if all elements in the Stream match a predicate function:

<T> boolean isAllEqualByAllMatch(T[] array) {
     // ... null and empty array handling
    return Arrays.stream(array)
      .allMatch(element -> Objects.equals(array[0], element));
}

This approach passes the same test:

assertTrue(isAllEqualByAllMatch(ARRAY_ALL_EQ));
assertTrue(isAllEqualByAllMatch(ARRAY_ALL_NULL));
assertTrue(isAllEqualByAllMatch(ARRAY_SINGLE_EL));
 
assertFalse(isAllEqualByAllMatch(ARRAY_NOT_EQ));
assertFalse(isAllEqualByAllMatch(ARRAY_EMPTY));
assertFalse(isAllEqualByAllMatch(ARRAY_NULL));

Next, let’s look at how to perform the same check for primitive arrays.

4. Primitive Arrays

We’ve seen different solutions for object arrays. In this section, let’s use int[] as examples to see how to check if all elements in a primitive array are equal.

So next, let’s first create some input examples:

final static int[] INT_ARRAY_ALL_EQ = { 7, 7, 7, 7 };
final static int[] INT_ARRAY_SINGLE_EL = { 42 };
 
final static int[] INT_ARRAY_NOT_EQ = { 7, 7, 7, 42 };

We have omitted null and empty array inputs, as there is no difference from the checks in object array solutions. Further, as primitive elements won’t be null, we don’t have the “ALL_NULL” case.

Next, let’s see how to perform the check on these int[] arrays.

4.1. Using Loop

We can use a quite similar loop-based implementation to check an int[]:

boolean isAllEqual(int[] array) {
    // ... null and empty array handling
    for (int i = 1; i < array.length; i++) {
        if (array[0] != array[i]) {
            return false;
        }
    }
    return true;
}

The above code looks pretty similar to the generic isAllEqual() implementation. However, it’s important to note that we should use ‘==’ to check the equality of two primitive variables.

It’s worth mentioning if we still use Objects.equals() method, the method works too, for example:

if (!Objects.equals(array[0], array[i])) {
    return false;
}

Let’s have a closer look at the Objects.equals() method:

public static boolean equals(Object a, Object b) {
    return (a == b) || (a != null && a.equals(b));
}

As the code shows, Objects.equals() accepts two Object instances. So, when we pass int values to it, int‘ll be autoboxed to its wrapper class Integer. Therefore, we used the ‘*!=*‘ check directly in our solution to avoid unnecessary autoboxing.

Our solution passes the tests:

assertTrue(isAllEqual(INT_ARRAY_ALL_EQ));
assertTrue(isAllEqual(INT_ARRAY_SINGLE_EL));
 
assertFalse(isAllEqual(INT_ARRAY_NOT_EQ));

To make isAllEqual () work with a different primitive type, we can replace the parameter type int[] with the desired primitive array type.

4.2. Using *Stream.*distinct() or Stream.allMatch()

Java offers primitive Stream types, such as IntStream, LongStream, etc., which allow us to work with primitive values and the Stream API without autoboxing between the wrapper types.

However, since there is no “ShortStream” class, we can use Arrays.stream(shortArray) to get a Stream of Short instances.

Next, let’s use IntStream‘s distinct() and allMatch() to perform required checks:

//distinct()
boolean isAllEqualByDistinct(int[] array) {
    // ... null and empty array handling
    return IntStream.of(array)
      .distinct()
      .count() == 1;
}

//test:
assertTrue(isAllEqualByDistinct(INT_ARRAY_ALL_EQ));
assertTrue(isAllEqualByDistinct(INT_ARRAY_SINGLE_EL));
 
assertFalse(isAllEqualByDistinct(INT_ARRAY_NOT_EQ));

//allMatch()
boolean isAllEqualByAllMatch(int[] array) {
    // ... null and empty array handling
    return IntStream.of(array)
      .allMatch(element -> array[0] == element));
}

//test:
assertTrue(isAllEqualByAllMatch(INT_ARRAY_ALL_EQ));
assertTrue(isAllEqualByAllMatch(INT_ARRAY_SINGLE_EL));
 
assertFalse(isAllEqualByAllMatch(INT_ARRAY_NOT_EQ));

As the code shows, changing the parameter type to int[] makes the methods work for int[] inputs.

5. Conclusion

In this article, we’ve explored different solutions to checking whether all elements in an array are equal and discussed how to use these approaches to check object and primitive arrays.

As always, the complete source code for the examples is available over on GitHub.