Reputation: 181
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?
Upvotes: 4
Views: 1455
Reputation: 424993
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;
Upvotes: 5
Reputation: 34460
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
Upvotes: 1
Reputation: 5831
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;
}
Upvotes: 0
Reputation: 610
for(int i = 0; i < arr.length-1; i++){
if(!arr[i].equals(arr[i+1])){
return false;
}
}
return true;
Upvotes: 0