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

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