Check if all elements in an array are equal in Java
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { int[] arr = {1, 1, 1, 1, 1}; Set<Integer> distinct = Arrays.stream(arr).boxed().collect(Collectors.toSet()); boolean allEqual = distinct.size() == 1; System.out.println(allEqual); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import com.google.common.collect.Sets; import com.google.common.primitives.Ints; public class Main { public static void main(String[] args) { int[] arr = {1, 1, 1, 1, 1}; boolean allEqual = Sets.newHashSet(Ints.asList(arr)).size() == 1; System.out.println(allEqual); } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] arr = {1, 1, 1, 1, 1}; boolean allEqual = Arrays.stream(arr).distinct().count() == 1; System.out.println(allEqual); } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] arr = {1, 1, 1, 1, 1}; boolean allEqual = arr.length == 1 || Arrays.stream(arr).allMatch(t -> t == arr[0]); System.out.println(allEqual); } } |
Output:
true
Here’s a version that works with Java 7 or less:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class Main { public static boolean isAllEqual(int[] arr) { if (arr == null || arr.length == 0) { return false; } for (int i = 1; i < arr.length; i++) { if (arr[0] != arr[i]) { return false; } } return true; } public static void main(String[] args) { int[] arr = {1, 1, 1, 1, 1}; System.out.println(isAllEqual(arr)); } } |
Output:
true
That’s all about checking if all elements in an array are equal.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)