CodesJava

Easy learning with example program codes

how to iterate a linkedhashset in java?


LinkedHashSet:

LinkedHashSet extends HashSet and implements the Set interface. It maintains insertion order for its elements.
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.Iterator;
import java.util.LinkedHashSet;
 
public class Test {
  public static void main(String args[]){
	//Create LinkedHashSet
	LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();
        //Add elements to LinkedHashSet
	linkedHashSet.add("Jai");
	linkedHashSet.add("Mahesh");
	linkedHashSet.add("Vikas");
	linkedHashSet.add("Sahil");
	linkedHashSet.add("Sachin");
	linkedHashSet.add("Vijay");
        Iterator<String> iterator = linkedHashSet.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
  }
}

Output

Jai
Mahesh
Vikas
Sahil
Sachin
Vijay


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap