Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how can I test if an Array contains the same value?

Tags:

java

arrays

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

like image 727
ternes3 Avatar asked Jan 16 '14 19:01

ternes3


3 Answers

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.

like image 40
Justin Niessner Avatar answered Oct 03 '22 07:10

Justin Niessner


if( new HashSet<String>(Arrays.asList(yourArray)).size() == 1 ){
    // All the elements are the same
}
like image 34
Dawood ibn Kareem Avatar answered Oct 03 '22 06:10

Dawood ibn Kareem


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)));


It comes quite complicated if there are only or any 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.

like image 148
Alexis C. Avatar answered Oct 03 '22 08:10

Alexis C.