简体   繁体   中英

A loop to compare all string values of an array

Let's say you have a string array arr with 3 strings in it. To compare its values, you would 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 that array had hundreds of strings? What is the best way to compare all the values?

I thought of using for loops but Java does not allow loops inside a conditional. Any ideas?

How about this 1-liner:

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

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

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

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

If the array could be of any dimension, then the Objects.deepEquals() method might be of help:

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

Even better:

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

Test:

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
for(int i = 0; i < arr.length-1; i++){
    if(!arr[i].equals(arr[i+1])){
        return false;
    }
}
return true;

A brute force method to do this is to compare the 1st string with every other string 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM