Skip to content

Java TreeMap Get All Values – values method Example

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

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

The values method of the TreeMap class returns all the values contained in the TreeMap object.

The values method returns a Collection view of all the values stored in the map object.

Output

Important Note:

The Collection object returned by the values method is a view that is backed by the original TreeMap object. That means any changes you make to the collection will be reflected in the TreeMap object, and vice versa.

Let’s have a look at an example of that.

Output

As you can see from the output, whatever changes you make to the values collection are also reflected in the original TreeMap object, and vice versa.

Please also note that the add and addAll operations are not supported by the Collection object obtained using the values method. If you try to add something to the values collections using these methods, the code will throw java.lang.UnsupportedOperationException exception as shown below.

Output

Please also visit how to get all keys 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.