Check whether array has all identical elements using Arrays.asList() and HashSet in Java
Last Updated :
18 Jun, 2019
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:
import java.util.*;
class GFG {
public static <T> void checkIdentical(T array[])
{
Set<T> set = new HashSet<>(Arrays.asList(array));
if (set.size() == 1 || set.isEmpty()) {
System.out.print( "Yes" );
}
else {
System.out.print( "No" );
}
}
public static void main(String args[])
{
Integer arr[] = { 2 , 2 , 2 , 2 , 2 , 2 };
checkIdentical(arr);
}
}
|
Share your thoughts in the comments
Please Login to comment...