I'm looking for a method to detect if all objects within an array(list) are the same. e. g:
arraylist1 = {"1", "1", "1", "1"} // elements are the same
arraylist2 = {"1", "1", "0", "1"} // elements are not the same
Thanks for help
public static boolean AreAllSame(String[] array)
{
boolean isFirstElementNull = array[0] == null;
for(int i = 1; i < array.length; i++)
{
if(isFirstElementNull)
if(array[i] != null) return false;
else
if(!array[0].equals(array[i])) return false;
}
return true;
}
Please feel free to correct any syntax mistakes. I fear my Java-fu may be lacking today.
if( new HashSet<String>(Arrays.asList(yourArray)).size() == 1 ){
// All the elements are the same
}
Java 8 solution :
boolean match = Arrays.stream(arr).allMatch(s -> s.equals(arr[0]));
Same logic for lists :
boolean match = list.stream().allMatch(s -> s.equals(list.get(0)));
null
values in the array (resulting in a NullPointerException
). So possible workarounds are:
Using Predicate.isEqual
, it uses the static method equals
from the Objects
class and it will do the null check for you before calling equals on the first argument.
boolean match = Arrays.stream(arr).allMatch(Predicate.isEqual(arr[0]));
boolean match = Arrays.stream(arr).allMatch(s -> Objects.equals(arr[0], s));
Using distinct()
and count()
:
boolean match = Arrays.stream(arr).distinct().count() == 1;
that can be improved into Arrays.stream(arr).distinct().limit(2).count() == 1;
as there is no need to check the all pipeline's content if you already find 2 distinct elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With