简体   繁体   English

用于比较数组的所有字符串值的循环

[英]A loop to compare all string values of an array

Let's say you have a string array arr with 3 strings in it. 假设你有一个包含3个字符串的字符串数组arr 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. 我想过使用for循环,但Java不允许在条件内循环。 Any ideas? 有任何想法吗?

How about this 1-liner: 这个1班轮怎么样:

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

This code neatly handles empty (but not null) arrays, returning false if empty. 此代码整齐地处理空(但不是null)数组,如果为空则返回false

If you want to return true when the array is empty, change the test to: 如果要在数组为空时返回true ,请将测试更改为:

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

If the array could be of any dimension, then the Objects.deepEquals() method might be of help: 如果数组可以是任何维度,那么Objects.deepEquals()方法可能会有所帮助:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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