Check whether array has all identical elements using Arrays.asList() and HashSet in Java
Given an array arr[] of N elements, the task is to check whether the array have all same (identical) elements or not without using the loop. If all elements are same then print Yes otherwise print No.
Examples:
Input: arr[] = {2, 2, 2, 2, 2}
Output: Yes
The given array has all identical elements i.e. 2.
Input: arr[] = {2, 3, 3, 3, 3, 2, 2}
Output: No
Approach: First, we check the size of array if the size of an array is 0 or 1 then the array is identical. If it’s size is > 1 then we take a set and copy all elements of an array in a set using Arrays.asList(). Then we calculate the size of the set, if the size of the set is 1, then the array has all identical elements otherwise not.
Below is the implementation of the above approach:
// Java implementation of the approach import java.util.*; class GFG { // Generic function to check whether the given array // has all identical element or not public static <T> void checkIdentical(T array[]) { // Create the Set by passing the Array // as parameter in the constructor Set<T> set = new HashSet<>(Arrays.asList(array)); // Check the size of set, f size is 0 or 1 then // array has only identical elements if (set.size() == 1 || set.isEmpty()) { System.out.print("Yes"); } else { System.out.print("No"); } } // Driver code public static void main(String args[]) { Integer arr[] = { 2, 2, 2, 2, 2, 2 }; checkIdentical(arr); } } |
Yes
Recommended Posts:
- Check if there exist two elements in an array whose sum is equal to the sum of rest of the array
- Check if an array contains all elements of a given range
- Check if all array elements are distinct
- Check if all elements of the array are palindrome or not
- Check if all elements of binary array can be made 1
- Check if a given array contains duplicate elements within k distance from each other
- HashSet in Java
- Check if the array has an element which is equal to XOR of remaining elements
- Check if array elements are consecutive | Added Method 3
- Check if the array has an element which is equal to sum of all the remaining elements
- Check if elements of an array can be arranged satisfying the given condition
- HashSet add() Method in Java
- How to sort HashSet in Java
- Traverse through a HashSet in Java
- HashSet vs TreeSet in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


