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)
.
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.
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With