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.
import java.util.*;
public class HSetHasHSetet {
public static void main(String [] args) {
System.out.println( "HashSet Example" );
int size;
// Create a HashSet
HasHSetetHSet = 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);
}
}
}
0 comments:
Post a Comment