Henry Zhu
Henry Zhu

Reputation: 2618

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

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

Upvotes: 7

Views: 3718

Answers (3)

gdejohn
gdejohn

Reputation: 7579

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

Upvotes: 8

Misha
Misha

Reputation: 28133

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.

Upvotes: 3

almightyGOSU
almightyGOSU

Reputation: 3739

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!

Upvotes: 3

Related Questions