In this example we will show how to check if a specified element exists in a HashSet in Java.
Source Code
package com.beginner.examples;
import java.util.HashSet;
public class ElementInHashSet {
public static void main(String[] args) {
// Create a HashSet object
HashSet sets = new HashSet();
sets.add("A");
sets.add("B");
boolean b = sets.contains("A"); // check if a specified element exists in a HashSet
System.out.println(b);
}
}
Output:
true
References
Imported packages in Java documentation: