Open In App

Java Program to Iterate LinkedHashSet Elements

Last Updated : 17 Sep, 2021
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. When cycling through LinkedHashSet using an iterator, the elements will be returned to the order in which they were inserted.

Different Ways to Iterate LinkedHashSet Elements:

  1. Using the for-each loop
  2. Using iterators
  3. Using JDK 1.8 streams

Method 1: Using the for-each loop


Output
Element is 1
Element is 2
Element is 3
Element is 4
Element is 5

Method 2: Using iterators


Output
Element is 1
Element is 2
Element is 3
Element is 4
Element is 5

Method 3: Using JDK 1.8 streams


Output
Element is  1
Element is  2
Element is  3
Element is  4
Element is  5

Similar Reads