Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Something like 'contains any' for Java set?

Tags:

java

I have two sets, A and B, of the same type.

I have to find if A contains any element from the set B.

What would be the best way to do that without iterating over the sets? The Set library has contains(object) and containsAll(collection), but not containsAny(collection).

like image 836
Rahul garg Avatar asked Jan 03 '12 06:01

Rahul garg


People also ask

Does set have Contains in Java?

Set contains() method in Java with ExamplesSet. contains() method is used to check whether a specific element is present in the Set or not. So basically it is used to check if a Set contains any particular element. Parameters: The parameter element is of the type of Set.

How do you check if a set contains an element in Java?

Check if Set Contains Element You can check if a Java Set contains a given element (object) by calling the contains() method. Here is an example of checking if a Java Set contains a given element: Set<String> set = new HashSet<>(); set. add("123"); set.

How do you check if a list contains any element of another list in Java?

ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.

How do you know if a set contains an object?

Use the has() method to check if a Set contains an object, e.g. set.has(obj) . The object has to be passed by reference to the has method to get a reliable result. The has method tests for the presence of a value in a Set and returns true if the value is contained in the Set .


1 Answers

Wouldn't Collections.disjoint(A, B) work? From the documentation:

Returns true if the two specified collections have no elements in common.

Thus, the method returns false if the collections contains any common elements.

like image 164
Frontline Avatar answered Sep 20 '22 22:09

Frontline