CodesJava

Easy learning with example program codes

how to iterate a hashset in java?


HashSet:

HashSet extends AbstractSet and implements the Set interface. It not maintains any order for its elements. It uses hash table for storage.

We can use iterator interface. It is a universal iterator as we can apply it to any Collection object. It provides the functionality of read and remove operations. Collection interface provides iterator() method to get the Iterator object. Iterator interface have following to methods to iterate collection objects.

  • hasNext(): It returns true if the iteration has more elements.
  • next(): It returns the next element in the iteration.

Example:

package com.codesjava;
 
import java.util.HashSet;
import java.util.Iterator;
 
public class Test {	 
    public static void main(String[] args) {
    	//Create HashSet object
    	HashSet<String> hashSet = new HashSet<String>();
        //Add elements to HashSet
    	hashSet.add("Jai");
    	hashSet.add("Mahesh");
    	hashSet.add("Vivek");
    	hashSet.add("Naren");
    	hashSet.add("Vishal");
    	hashSet.add("Hemant");
        Iterator<String> iterator = hashSet.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

Output

Naren
Jai
Vivek
Hemant
Mahesh
Vishal


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap