Java - HashSet
Java HashSet is a class that implements the Set interface and extends the AbstractSet class. It is used to create a collection that contains no duplicate elements. It stores the elements in a hash table, which provides a constant-time performance for the basic operations like adding, removing, and searching elements in the set. The HashSet does not maintain the order of elements in the set.
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Apple"); // duplicate value
System.out.println(set); // output: [Cherry, Apple, Banana]
System.out.println("Size of set: " + set.size()); // output: 3
set.remove("Banana");
System.out.println(set); // output: [Cherry, Apple]
System.out.println("Size of set: " + set.size()); // output: 2
}
}
In the example above, we first create an instance of the HashSet class, and then add four elements to it. Note that the duplicate value "Apple" is added twice, but it is stored in the set only once, because HashSet does not allow duplicate elements. We then print out the set and its size.
Next, we remove the element "Banana" from the set, and print out the updated set and its size.
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
HashSet<String> mySet = new HashSet<>();
// Add elements to the HashSet
mySet.add("apple");
mySet.add("banana");
mySet.add("cherry");
mySet.add("banana"); // Duplicate element
// Print the HashSet
System.out.println("HashSet: " + mySet);
// Check if an element is present in the HashSet
System.out.println("Is 'banana' present? " + mySet.contains("banana"));
// Remove an element from the HashSet
mySet.remove("cherry");
// Print the HashSet again
System.out.println("HashSet after removal: " + mySet);
// Loop through the HashSet
System.out.print("Elements of the HashSet: ");
for (String element : mySet) {
System.out.print(element + " ");
}
}
}
In this example, we create a HashSet object mySet and add four elements to it, including a duplicate element "banana". We then print the HashSet, check if an element "banana" is present, remove an element "cherry", and loop through the HashSet to print its elements.