Skip to content

Java TreeMap Get All Keys – keySet method Example

This example shows how to get all keys of the TreeMap object using the keySet method of the TreeMap class. The example also shows how to iterate all keys of the TreeMap object.

How to get all keys of TreeMap using the keySet method in Java?

The keySet method of the TreeMap class returns a Set view of the keys contained in the TreeMap object.

The returned Set object contains all keys present in the TreeMap object.

Output

Important Note:

The Set returned from the keySet method is a view that is backed by the original TreeMap object. It means any changes you make to the key set will be reflected in the TreeMap object, and vice versa.

Output

As you can see from the output when we change the key set the TreeMap also changed, and vice versa.

However, remember that add and addAll operations are not supported by the key set. Have a look at the below given example.

Output

As you can see from the output if you try to use add or addAll methods of the Set, the code will throw java.lang.UnsupportedOperationException exception as these operations are not supported by the key set.

Please also visit how to get all values of TreeMap example.

This example is a part of the Java TreeMap Tutorial with Examples.

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.