Java TreeMap forEach Example

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

How to iterate TreeMap using the forEach?

There are several ways using which you can iterate TreeMap keys, values, and entries using the forEach. Please remember that you will need Java version 8 or later in order to use the forEach construct.

1. Iterate TreeMap keys using forEach

The keySet method returns a Set view of all the keys contained in the TreeMap object. Once we get that, we can iterate through the keys using the forEach as given below.

Output

2. Iterate TreeMap values using forEach

The values method returns a Collection view of all the values contained in the TreeMap object. Once we get the Collection, we can iterate through the values using the forEach as given below.

Output

3. Iterate TreeMap entries using forEach

The entrySet method of the TreeMap object returns a Set view of all the entries (i.e. key-value mappings) stored in the map object. Once we get the Set, we can iterate through TreeMap entries using the forEach as given below.

Output

Please also visit how to iterate TreeMap example to know more ways to iterate the TreeMap object.

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

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

References:
Java 8 TreeMap

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