Tutorials

Java Collection Programs


LinkedHashSet traversal


In this chapter, our task is:

  • We will create a LinkedHashSet
  • We will add elements to LinkedHashSet (duplicate as well)
  • Traverse the LinkedHashSet using Iterator 
  • We will print the set

LinkedHashSet is almost similar to HashSet except it maintains the insertion order of the element.

Maintains the insertion order indicates that elements will be returned in same order in which they were inserted in the Set.

Example: Traverse elements of LinkedHashSet using Iterator in java

 

package javaRadarLinkedHashSet;

import java.util.Iterator;
import java.util.LinkedHashSet;

public class SimpleLHS {

      public static void main(String[] args) {

        //create LinkedHashSet
          LinkedHashSet javaRadarSet = new LinkedHashSet();

        //Add elements to LinkedHashSet
          javaRadarSet.add("Java");
          javaRadarSet.add("Java");
          javaRadarSet.add("Spring");
          javaRadarSet.add("Hibernate");
          javaRadarSet.add("EJB");

        //creating iterator to traverse over javaRadarSet
          Iterator setIterator = javaRadarSet.iterator();

            while(setIterator.hasNext()){

               System.out.println(setIterator.next());

            }

       }

}

OUTPUT

Java
Spring
Hibernate
EJB
 
To read in detail about LinkedHashSet in java, click here

 



Please Share this page
Views : 50
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!