How To Loop Over HashSet In Java

By Following ways we can Loop Over HashSet

1.by using Iterator

by using for loop

lets see example one by one

Example to Loop Over HashSet by using Iterator.


package com.java2study;

import java.util.HashSet;
import java.util.Iterator;

public class HashSetDemo{


public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add("AAAA");
hashSet.add("BBBB");
hashSet.add("CCCC");
hashSet.add("DDDD");
System.out.println("The HashSet elements:"+hashSet);




Iterator iterator = hashSet.iterator();

while(iterator.hasNext()){

System.out.println(iterator.next());
}

}



}


output


The HashSet elements:[DDDD, AAAA, BBBB, CCCC]
DDDD
AAAA
BBBB
CCCC

Example to Loop Over HashSet by using for loop.


package com.java2study;

import java.util.HashSet;
import java.util.Iterator;

public class HashSetDemo{


public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add("AAAA");
hashSet.add("BBBB");
hashSet.add("CCCC");
hashSet.add("DDDD");
System.out.println("The HashSet elements:"+hashSet);

for(String s:hashSet){
System.out.println(s);
}


}



}


output


The HashSet elements:[DDDD, AAAA, BBBB, CCCC]
DDDD
AAAA
BBBB
CCCC

No comments:

Post a Comment