Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to test if an Array contains the same value?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading