Java HashMap forEach for loop example

This Java HashMap forEach for loop example shows how to iterate HashMap keys, values, or entries using the forEach loop and for loop.

How to Iterate HashMap using forEach and for loop?

How to iterate all keys of HashMap using for loop?

First, get all the keys of the map using the keySet method and then iterate over them one by one using the enhanced for loop as given in the below example.

Output

How to iterate all values of HashMap using for loop?

Get all the values contained in the HashMap object using the values method and then iterate over them as given below.

Output

How to iterate all mappings of HashMap using for loop?

Get all the entries contained in the HashMap using the entrySet method of the HashMap class and then iterate over them using the for loop as given below.

Output

How to iterate all mappings of HashMap using forEach? (Java 8 and later)

If you are using Java 8 or later version, you can use the forEach to iterate over all the mappings of the HashMap as given below.

Output

Please visit How to iterate HashMap example to know more ways to iterate over the HashMap in Java.

This example is a part of the HashMap in Java tutorial.

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

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 *