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

I am looking for a method to determine if all objects in 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 the help

+4
source share
8 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 errors. I am afraid my Java-fu might be out today.

+10
source

Java 8 solution:

boolean match = Arrays.stream(arr).allMatch(s -> s.equals(arr[0]));

The same logic for lists:

boolean match = list.stream().allMatch(s -> s.equals(list.get(0)));

<h / "> This is quite difficult if the array contains only or any values null(as a result NullPointerException). Possible workarounds:

  • Predicate.isEqual, equals Objects, equals .

    boolean match = Arrays.stream(arr).allMatch(Predicate.isEqual(arr[0]));
    boolean match = Arrays.stream(arr).allMatch(s -> Objects.equals(arr[0], s));

  • distinct() count():

    boolean match = Arrays.stream(arr).distinct().count() == 1;

    Arrays.stream(arr).distinct().limit(2).count() == 1;, , .

+18
if( new HashSet<String>(Arrays.asList(yourArray)).size() == 1 ){
    // All the elements are the same
}
+5

, true. , , 0. , true, false.

+2
 public boolean containsSameValues(int[] array) {
     if(array.length == 0) {
         throw new IllegalArgumentException("Array is empty");
     }
     int first = array[0];
     for(int i=0;i<array.length;i++) {
         if(array[i] != first) {
             return false;
         }
      }
      return true;
 }
+1
boolean containsAllValues=false;
boolean t=false;
int isto=0; 
for(int k=0;k<arraylist1.size();k++){
   for(int n=0;n<arraylist2.size();n++){
       if(arraylist1.get(k).equals(arraylist2.get(n))){
           t=true;
       }
   }
   if(t){
       isto++;
   }else{
       isto=0;
       break;
   }
}
if(isto!=0){
   containsAllValues=true;
}

, arraylist2 arraylist1.

+1

, :

public boolean equalArrays(int []f ,int [] g){
        Arrays.sort(f);
        Arrays.sort(g);
        if (Arrays.equals(f, g))
             return true;
        return false;
}

:

         int [] h={1,1,0,1};
         int [] t={1,1,1,0};
         System.out.println(cc.equalArrays(h,t));
+1

Java 8 Alexis C, , . , <= Java 7 , , :

boolean result = Collections.frequency(yourList, "1") == yourList.size();

, , , "1" . .

, Java Collections API, , Collection.frequency(..) , , JDK 1.5. . javadocs.

EDIT: , .

+1

All Articles