0

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.

Community
  • 1
  • 1
Sait
  • 19,045
  • 18
  • 72
  • 99

4 Answers4

5

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

boolean hasDuplicateValue(HashSet hs1, HashSet hs2) {        
  return !Collections.disjoint(hs1,hs2);
}
Simiil
  • 2,281
  • 1
  • 22
  • 32
4

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

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.

Dimitri
  • 8,122
  • 19
  • 71
  • 128
0

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;
}
fluminis
  • 3,575
  • 4
  • 34
  • 47
  • Good advice. I just took the method signature from question body. Thought it would be most relevant :) –  Sep 30 '13 at 08:40