To remove elements from a HashSet in Java, you can use the remove() method of the HashSet class. The remove() method removes the specified element from the set if it is present.
Here's an example:
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
HashSet<String> set = new HashSet<>();
// Add elements to the HashSet
set.add("apple");
set.add("banana");
set.add("cherry");
set.add("orange");
// Print the HashSet
System.out.println("HashSet before removing an element: " + set);
// Remove an element from the HashSet
set.remove("banana");
// Print the HashSet after removing an element
System.out.println("HashSet after removing an element: " + set);
}
}
In this example, we create a HashSet of strings and add some elements to it. We then remove the element "banana" using the remove() method and print the HashSet before and after removing the element.
The output of the above code will be:
HashSet before removing an element: [orange, apple, cherry, banana]
HashSet after removing an element: [orange, apple, cherry]
As you can see, the element "banana" has been removed from the HashSet.