Skip to content

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

Leave a Reply

Your email address will not be published.