7

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"};
Henry Zhu
  • 2,488
  • 9
  • 43
  • 87
  • LinkedHashSet holds only unque elements. So, do like this, Set arrToSet = new LinkedHashSet(Arrays.asList(hands)); OR Collection arrToSet = new LinkedHashSet(Arrays.asList(arr)); – bobs_007 Jul 01 '15 at 00:54
  • http://stackoverflow.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist – bobs_007 Jul 01 '15 at 00:56
  • Define different. Different values? Different objects? If you are asking specifically about the strings in your sample code, do you care about case-sensitive comparison? – Chamatake-san Jul 01 '15 at 01:02

3 Answers3

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

gdejohn
  • 7,451
  • 1
  • 33
  • 49
3

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!
almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
3

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.

Misha
  • 27,433
  • 6
  • 62
  • 78