Sait
Sait

Reputation: 19805

Find out whether two HashSets have a duplicate value

I need a function like the following,

boolean hasDuplicateValue(HashSet hs1, HashSet hs2) {        
    // return false;
}

This thread Efficiently finding the intersection of a variable number of sets of strings discusses a similar issue, however in this thread they also need the intersection values, which I do not need. So, it may add an additional computational complexity which I do not need.

Upvotes: 0

Views: 848

Answers (4)

Simiil
Simiil

Reputation: 2311

The java.util.Collections class provides useful methods for that:

boolean hasDuplicateValue(HashSet hs1, HashSet hs2) {        
  return !Collections.disjoint(hs1,hs2);
}

Upvotes: 5

user2813148
user2813148

Reputation:

Im not sure but do you talking about something like this ?

boolean hasDuplicateValue(HashSet hs1, HashSet hs2) {
    // you can add some null pointer defence if necessary
    if (hs2.size() == 0) {
        return false;
    }
    for (Object obj : hs1) {
        if (hs2.contains(obj)) {
            return true;
        }
    }
    return false;
}

Upvotes: 4

fluminis
fluminis

Reputation: 4059

To complete oleg.lukyrych answer: If you want to remove the warnings, on the declaration of the method: And it is a good practice to use Set instead of HashSet when possible :

<T> boolean hasDuplicateValue(Set<T> hs1, Set<T> hs2) {
    for (T obj : hs1) {
        if (hs2.contains(obj)) {
            return true;
        }
    }
    return false;
}

Upvotes: 0

Dimitri
Dimitri

Reputation: 8280

Take a look at the guava-libraries that provide a Sets which contains the intersect method. On the other side, this method takes two Set, not their implementation.

Upvotes: 0

Related Questions