Skip to content

Java LinkedHashSet Iterate Example

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.

Output

2. Iterate using the Iterator

We can get an iterator over the LinkedHashSet elements using the iterator method.

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.

Output

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.

Output

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

About the author

Leave a Reply

Your email address will not be published.