Iterate LinkedHashMap in Java Example

This example shows how to iterate LinkedHashMap in Java. The example also shows various ways to iterate over LinkedHashMap keys, values and entries using an iterator and for loop.

How to iterate LinkedHashMap in Java?

There are various ways using which you can iterate over keys, values, and entries of the LinkedHashMap object in Java.

How to iterate over keys?

The entrySet method of the LinkedHashMap class returns a Set view of all the keys contained in the map. You can then iterate through keys as given below.

Using for loop

You can use the for loop to iterate through all the keys as given below.

Using an Iterator

Alternatively, you can obtain an iterator object for the key set and iterate through the keys using the hasNext and the next methods of the Iterator.

Output

How to iterate over values?

The values method of the LinkedHashMap class returns a Collection view of all the values contained in the LinkedHashMap object. You can then iterate through them as given below.

Using for loop

Using an Iterator

You can also iterate through values using the hasNext and the next methods of the iterator as given below.

Output

How to iterate over entries (key-value mappings)?

The entrySet method of the LinkedHashMap class returns a Set view of all the entries (key-value mappings) contained in the LinkedHashMap object. You can then iterate through the mappings of the LinkedHashMap as given below.

Using for loop

Using an Iterator

You can also obtain an iterator for the entry set using the iterator method and then iterate using the hasNext and the next methods as given below.

Output

This example is a part of the LinkedHashMap in Java Tutorial.

Please let me know your views in the comments section below.

References:
Java 8 LinkedHashMap

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping