How to check if array elements are different java

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

I have an array line below:

 String[] hands = {"Zilch", "Pair", "Triple", "Straight", "Full House"}; 
+7
java arrays
source share
3 answers

How about using a HashSet and comparing a Hashset size with the length of the original array?
HashSet gets rid of duplicates, so if the size is the same as the length of the array, this will mean that all elements of the array are different.

Example:

 import java.util.Arrays; import java.util.HashSet; public class QuickTester { public static void main(String[] args) { String[] hands = new String[]{"Zilch", "Pair", "Triple", "Straight", "Full House"}; HashSet<String> hs = new HashSet<>(Arrays.asList(hands)); if(hs.size() == hands.length) { System.out.println("All elements in array are different!"); } else { System.out.println("Duplicates found in array!"); } hands = new String[]{"Banana", "Apple", "Orange", "Banana"}; hs = new HashSet<>(Arrays.asList(hands)); if(hs.size() == hands.length) { System.out.println("All elements in array are different!"); } else { System.out.println("Duplicates found in array!"); } } } 

Output:

 All elements in array are different! Duplicates found in array! 
+3
source share
 boolean noDupes(Object[] array) { return Arrays.stream(array).allMatch(new HashSet<>()::add); } 

Stop as soon as it finds a duplicate, and does not go through the entire array and compares the sizes at the end. Conceptually the same as Misha's answer , but it works at a higher level using Java 8 features (streams and method links).

+6
source share

No, there is no such method, but it is very easy to write:

 static boolean allUnique(String[] strings) { HashSet<String> set = new HashSet<>(); for (String s : strings) { if (! set.add(s)) { return false; } } return true; } 

Unlike the methods suggested in other answers, this will lead to a short circuit after detecting a duplicate.

+3
source share

All Articles