This post will discuss how to check if an element is present in a Set in Java.

1. Using Set.contains() method

The standard solution to check if an element is present in a Set is using the contains(o) method. It returns true if the set contains an element e such that Objects.equals(o, e) holds.

Download  Run Code

 
Note that if a class does not override the equals() and hashCode() methods, the default implementation of these methods only checks for the reference equality. In order words, if an object of such class is inserted in a Set, the contains() method will return false. For instance, consider the following code which returns false:

Download  Run Code

 
To fix this, simply override equals and hashCode methods. Both these methods can be auto-generated by IDE (Eclipse, IntelliJ IDEA, etc.).

Download  Run Code

2. Using Stream.anyMatch() method

In Java 8 and above, you can use the Stream.anyMatch() method that returns true if any element of the stream matches with the specified predicate.

Download  Run Code

3. Using Apache Commons Collections

If your project uses the Apache Commons Collections library, you may use the CollectionUtils.containsAny() method, which returns true if any element of the collection matches with any of the specified elements.

Download Code

4. Using Collections.disjoint() method

Finally, you can use the Collections.disjoint() method in Java, which returns true if the two specified collections have no elements in common. However, this method may suffer from the overhead caused by creating a collection containing the value to be searched.

Download  Run Code

That’s all about checking if an element is present in a Set in Java.