HashSet_Example.java
package com.alok;
import
java.io.IOException;
import java.util.*;
public class HashSet_Example
{
public static void main(String[]
args)throws IOException
{
String str[]={"alok","manish","Pravin","rajiv","pratyush"};
//create a HashSet to store
above string
HashSet<String> hs= new
HashSet<String>();
//Storing elements to HashSet
for(int i=0;i<str.length;i++)
{
hs.add(str[i]);
}
System.out.println(hs);
//add an iterator to HashSet
Iterator<String> it=
hs.iterator();
//Displaying elements using
iterator
System.out.println("Retrieve
Elements from HashSet using Iterator..");
while(it.hasNext())
{
String s=it.next();
System.out.println(s);
}
//Displaying Elements using
For-each loop...
System.out.println("\nRetrieve
Elements using for loop....");
for(String var:hs)
{
System.out.println(var);
}
}
}
OUTPUT
[manish, alok, Pravin, pratyush, rajiv]
Retrieve Elements from HashSet using Iterator..
manish
alok
Pravin
pratyush
rajiv
Retrieve Elements using for loop....
manish
alok
Pravin
pratyush
rajiv
No comments:
Post a Comment