Skip to content

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

Leave a Reply

Your email address will not be published.