Skip to content

Java LinkedHashMap forEach Example

This example shows how to iterate LinkedHashMap in Java using forEach. This example also shows how to iterate LinkedHashMap keys, values and entries using Java 8 forEach.

How to iterate LinkedHashMap using forEach?

If you are using Java version 8 or above, you can use the lambda expression and forEach method from the aggregate operations. You can iterate LinkedhashMap keys, values and entries (mapping of key-value pairs).

How to iterate all keys using forEach?

Use the keySet method of the LinkedHashMap class and then use the forEach to iterate over all keys.

Output

How to iterate all values using forEach?

You can use the values method of the LinkedHashMap class to get all values from the map and then use forEach to iterate over them as given below.

Output

How to iterate all entries using forEach?

The above two examples show how to iterate all keys and values of the LinkedHashMap individually. What if you want both keys and values at the same time?

Well, in that case, you can get all the entries (i.e. key-value mappings) from the LinkedHashMap object using the entrySet method. Once you get the Set of entries, you can use the forEach as given below.

Output

Please also visit how to Iterate LinkedHashMap in various other ways.

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

Leave a Reply

Your email address will not be published.