Loop to compare all string values ​​of an array

Say you have an arr string array with 3 lines in it. To compare its values, you simply do the following:

if (arr[0].equals(arr[1]) && arr[0].equals(arr[2] && arr[1].equals(arr[2]) {
    return true;
}

But what if there were hundreds of rows in this array? What is the best way to compare all values?

I was thinking of using for loops , but Java does not allow loops inside a conditional expression. Any ideas?

+4
source share
4 answers

How about this 1 liner:

return Arrays.stream(arr).distinct().count() == 1;

This code neatly handles empty (but not null) arrays, returning falseif empty.

If you want to return truewhen the array is empty, change the test to:

return Arrays.stream(arr).distinct().count() < 2;
+5

, Objects.deepEquals() :

boolean allEqual = Arrays.stream(arr).allMatch(a -> Objects.deepEquals(arr[0], a));

:

boolean allEqual = Arrays.stream(arr, 1, arr.length) // bounds check left
    .allMatch(a -> Objects.deepEquals(arr[0], a));   // to the reader :)

:

String[][] arr = {
    {"a", "a"},
    {"a", "a"},
    {"a", "a"}};

boolean allEqual = Arrays.stream(arr, 1, arr.length)
        .allMatch(a -> Objects.deepEquals(arr[0], a));

System.out.println(allEqual); // true
+1
for(int i = 0; i < arr.length-1; i++){
    if(!arr[i].equals(arr[i+1])){
        return false;
    }
}
return true;
0

The brute force method for this is to compare the 1st row with any other row in the array.

public boolean allUnique(String[] arr){
    //Assuming the array has at least 1 element. 
    String s = arr[0];
    for(int i = 1; i < arr.length; i++){
        if(!arr[i].equals(s)){
            return false;
        }   
    }
    return true;
}
0
source

Source: https://habr.com/ru/post/1628760/


All Articles