This example shows how to iterate over Java LinkedHashSet elements. The example also shows how to iterate through LinkedHashSet elements using for loop, Iterator, and forEach method.
How to iterate LinkedHashSet in Java?
There are several ways using which we can iterate through LinkedHashSet elements in Java as given below.
1. Iterate using the for loop
We can use the enhanced for loop to iterate over elements of the LinkedHashSet objects as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.LinkedHashSet; public class LinkedHashSetIterateExample { public static void main(String[] args) { LinkedHashSet<String> lhSetWeekDays = new LinkedHashSet<String>(); lhSetWeekDays.add("Monday"); lhSetWeekDays.add("Tuesday"); lhSetWeekDays.add("Wednesday"); lhSetWeekDays.add("Thursday"); lhSetWeekDays.add("Friday"); //iterating LinkedHashSet using enhanced for loop for( String strDay : lhSetWeekDays ){ System.out.println( strDay ); } } } |
Output
1 2 3 4 5 |
Monday Tuesday Wednesday Thursday Friday |
2. Iterate using the Iterator
We can get an iterator over the LinkedHashSet elements using the iterator
method.
1 |
public Iterator<E> iterator() |
Once we get an Iterator for the linked hash set object, we can use the hasNext
method and the next
method along with the while loop to iterate through its elements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
LinkedHashSet<String> lhSetWeekDays = new LinkedHashSet<String>(); lhSetWeekDays.add("Monday"); lhSetWeekDays.add("Tuesday"); lhSetWeekDays.add("Wednesday"); lhSetWeekDays.add("Thursday"); lhSetWeekDays.add("Friday"); //get an Iterator Iterator<String> iterator = lhSetWeekDays.iterator(); //iterating using the iterator and a while loop while( iterator.hasNext() ){ System.out.println( iterator.next() ); } |
Output
1 2 3 4 5 |
Monday Tuesday Wednesday Thursday Friday |
3. Iterate using the forEach method
If you are using Java version 8 or later, you can use the forEach
method of the Iterables to iterate over LinkedHashSet elements as given below.
1 2 3 4 5 6 7 8 9 10 11 12 |
LinkedHashSet<String> lhSetWeekDays = new LinkedHashSet<String>(); lhSetWeekDays.add("Monday"); lhSetWeekDays.add("Tuesday"); lhSetWeekDays.add("Wednesday"); lhSetWeekDays.add("Thursday"); lhSetWeekDays.add("Friday"); //iterating using forEach lhSetWeekDays.forEach( element -> { System.out.println( element ); }); |
Output
1 2 3 4 5 |
Monday Tuesday Wednesday Thursday Friday |
Note:
Unlike the HashSet class in Java, the LinkedHashSet class maintains a doubly-linked list running through all of its elements and guarantees the order of elements. It means you will get the elements in the same order in which they were inserted using any of the above given methods.
This example is a part of the Java LinkedHashSet Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 LinkedHashSet