Java – Searching a HashSet for any element in a string array

arrayshashsetjavasearchstring

I have a HashSet of strings and an array of strings. I want to find out if any of the elements in the array exists in the HashSet. I have the following code that work, but I feel that it could be done faster.

public static boolean check(HashSet<String> group, String elements[]){
    for(int i = 0; i < elements.length; i++){
        if(group.contains(elements[i]))
            return true;
    }
    return false;
}

Thanks.

Best Answer

It's O(n) in this case (array is used), it cannot be faster.

If you just want to make the code cleaner:

 return !Collections.disjoint(group, Arrays.asList(elements));