Set.contains() method in Java is used to check if a specific element exists in a Set. It returns true if the element is present, otherwise false. This method is useful for quickly verifying membership in collections that do not allow duplicates, like HashSet or TreeSet.
Example:
import java.util.*;
public class GFG {
public static void main(String[] args) {
Set<String> fruits = new HashSet<>();
fruits.add("Apple");
System.out.println("Does the set contain Apple?: " + fruits.contains("Apple"));
System.out.println("Does the set contain Orange?: " + fruits.contains("Orange"));
}
}
Output
Does the set contain Apple?: true Does the set contain Orange?: false
Explanation:
- Set<String> fruits = new HashSet<>(): creates a HashSet.
- contains() checks whether "Apple" and "Orange" exist in the set.
- "Apple" exists, so it returns true; "Orange" does not, so it returns false.
Syntax
boolean contains(Object element)
- Parameters: "element" to check for in the set.
- Return Value: returns true if the set contains the specified element, false otherwise
Example:This code shows how Set.contains() checks for an element in a HashSet.
import java.util.*;
public class HashSetDemo {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Welcome");
set.add("To");
set.add("Geeks");
set.add("4");
set.add("Geeks");
System.out.println("Set: " + set);
System.out.println("Does the Set contain 'Geeks'?: " + set.contains("Geeks"));
System.out.println("Does the Set contain '4'?: " + set.contains("4"));
System.out.println("Does the Set contain 'No'?: " + set.contains("No"));
}
}
Output
Set: [4, Geeks, Welcome, To] Does the Set contain 'Geeks'?: true Does the Set contain '4'?: true Does the Set contain 'No'?: false
Explanation:
- Duplicate entries are ignored automatically in a Set.
- contains() checks for the presence of an element in the set.
- The method returns true for existing elements and false for elements not in the set.
Note:Works for all Set types (HashSet, TreeSet, LinkedHashSet), has O(1) time complexity for HashSet.contains().