Write A Program In Java To Create A New Hashset, Add Colors(In String Form) And Iterate Through All Elements Using For-each Loop To Display The Collection
Before demonstrate the program we will understand the concept of Hashset.
In Java, HashSet is a class that implements the Set interface, and is used to store a collection of unique elements. HashSet is based on the hash table data structure, and provides constant-time performance for the basic operations like add(), contains(), and remove().
HashSet does not allow duplicate elements. If you try to add an element that is already in the set, it will simply be ignored.
HashSet allows null elements. You can add null to a HashSet and it will be treated as a unique element.
The size of a HashSet can be obtained using the size() method.
Here's an example program in Java that creates a new HashSet, adds colors in string form, and iterates through all the elements using a for-each loop to display the collection:
import java.util.HashSet;import java.util.Set;
public class HashSetExample {
public static void main(String[] args) {
// Create a new HashSet of strings for colors Set<String> colors = new HashSet<>();
// Add colors to the HashSet colors.add("Red"); colors.add("Green"); colors.add("Blue"); colors.add("Yellow"); colors.add("Orange");
// Iterate through all elements in the HashSet and print them for (String color : colors) { System.out.println(color); } }}
Red
Blue
Yellow
Orange
Green