HashSet Collection Sample Program Code

Sample Program on HashSet Collection:

A HashSet is a collection set that neither allows duplicate elements nor order or position its elements.

HashSet Methods

* add() method is used to insert an element in the HashSet collection.
* size() method helps you in getting the size of the collection.
* remove() method will be used to delete an element in the HashSet collection.
* clear() method is used to remove all data from the HashSet collection.

Sample program: HashSet program shows the methods to add, remove and iterate the values of collection. Keys will be used to put and get values. When the HashSet is empty, the below program checks and will display a message "Collection is not having any Elements". If the collection is having Elements then program displays the size of HashSet collection.

import java.util.*;

public class HSetHasHSetet {
public static void main(String [] args) {
System.out.println( "HashSet Example" );
int size;

// Create a HashSet
HasHSetet HSet = new HasHSetet ();
String string1 = "Yellow", string2 = "White",
string3 = "Green", string4 = "Blue";
Iterator iterator;

//Adding data in to HashSet
HSet.add(string1);
HSet.add(string2);
HSet.add(string3);
HSet.add(string4);
System.out.print("HashSet data: ");

//Create a iterator
iterator = HSet.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();

// Get size of a HSet
size = HSet.size();
if (HSet.isEmpty()){
System.out.println("HashSet is empty");
}
else{
System.out.println( "HashSet size: " + size);
}
System.out.println();

// Remove specific data
HSet.remove(string2);
System.out.println("After removing [" + string2 + "]\n");
System.out.print("Now HashSet data: ");
iterator = HSet.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
size = HSet.size();
System.out.println("HashSet size: " + size + "\n");

//HashSet empty
HSet.clear();
size = HSet.size();
if (HSet.isEmpty()){
System.out.println("Collection is not having any Elements");
}
else{
System.out.println( "HashSet size: " + size);
}
}
}

No comments:

Post a Comment