Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Check if an Array's Elements are All Different Java

Tags:

java

arrays

Is their any predefined function in Java such that I can check if all the elements in an array are different? Or do I have to write a function from scratch to find it?

I have a String array below:

String[] hands = {"Zilch", "Pair", "Triple", "Straight", "Full House"};
like image 906
Henry Zhu Avatar asked Jul 01 '15 00:07

Henry Zhu


1 Answers

boolean noDupes(Object[] array) {
    return Arrays.stream(array).allMatch(new HashSet<>()::add);
}

Stops as soon as it finds a duplicate, rather than going through the entire array and comparing sizes at the end. Conceptually the same as Misha's answer, but using Java 8 functional programming features (streams and method references).

like image 76
gdejohn Avatar answered Oct 29 '22 01:10

gdejohn