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
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.
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:
null
NullPointerException
Predicate.isEqual, equals Objects, equals .
Predicate.isEqual
equals
Objects
boolean match = Arrays.stream(arr).allMatch(Predicate.isEqual(arr[0]));boolean match = Arrays.stream(arr).allMatch(s -> Objects.equals(arr[0], s));
boolean match = Arrays.stream(arr).allMatch(Predicate.isEqual(arr[0]));
boolean match = Arrays.stream(arr).allMatch(s -> Objects.equals(arr[0], s));
distinct() count():
distinct()
count()
boolean match = Arrays.stream(arr).distinct().count() == 1;
Arrays.stream(arr).distinct().limit(2).count() == 1;, , .
Arrays.stream(arr).distinct().limit(2).count() == 1;
if( new HashSet<String>(Arrays.asList(yourArray)).size() == 1 ){ // All the elements are the same }
, true. , , 0. , true, false.
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; }
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.
, :
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));
Java 8 Alexis C, , . , <= Java 7 , , :
boolean result = Collections.frequency(yourList, "1") == yourList.size();
, , , "1" . .
Collections API
Collection.frequency(..)
EDIT: , .