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

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).


How about using a HashSet and comparing the size of the Hashset with the length of the original array?
HashSet gets rid of duplicates, so if the size is the same as the array length, it will mean that all array elements 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!

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

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

Unlike methods offered in other answers, this will short-circuit once a duplicate is found.

Tags:

Java

Arrays