Skip to content

Java TreeMap Iterate Example

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

How to iterate TreeMap in Java?

There are various ways using which you can iterate through TreeMap keys, value or entries as given below.

1. How to iterate all keys of TreeMap?

The keySet method of the TreeMap class returns a Set view of all the keys stored in the TreeMap object. We can then iterate through keys using below given ways.

Using for loop

Using an Iterator

Using forEach

Output

2. How to iterate all values of TreeMap?

The values method of the TreeMap class returns a Collection view of all the values stored in the TreeMap object. We can then iterate through all the values using below given ways.

Using for loop

Using an Iterator

Using forEach

Output

3. How to iterate all entries of TreeMap?

The entrySet method of the TreeMap class returns a Set view of all the entries contained in the TreeMap object. We can then iterate through the entries using below given ways.

Using the for loop

Using an Iterator

Using the forEach

Output

Please also visit Java TreeMap forEach example.

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.