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

0

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

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:


Program
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);
        }
    }
}

Output
Red Blue Yellow Orange Green
Note that the order of elements in a HashSet is not guaranteed, so the output may be in a different order than the order in which the elements were added to the HashSet.

Explanation
In this program, we first import the HashSet, Set, and java.util package.

Then, we create a new HashSet of strings called colors.

Next, we add five string elements to the colors HashSet using the add() method.

We then iterate through all the elements in the colors HashSet using a for-each loop, and print each element to the console using the println() method.

❤️ I Hope This Helps You Understand, Click Here To Do More Exercise In Java Programming.

Post a Comment

0Comments
Post a Comment (0)