How can I check the if all elements in an array are the same?
This is the only solution that came to my mind. I wonder if is there any efficent one?
public boolean isSame(int [] arr) {
Set<Integer> set = Arrays.stream(arr).boxed().collect(Collectors.toSet());
return set.size() == 1;
}
>Solution :
As @Jim Garrison says, a loop would be the most efficient since you could exit as soon as you encounter a differing value.
However, assuming you want to keep it succinct, you might prefer:
IntStream.of(arr).distinct().count();
Which can be re-used if you want to determine the exact number distinct values.
However, if you just want to return true if they’re all the same, I must recommend @Eritean’s suggestion, which eliminates much of the overhead:
IntStream.of(arr).allMatch(i -> i == arr[0]);