In this shot, we will learn how to use the TreeMap.values()
method in Java, which is present in the TreeMap
class inside the java.util
package.
The TreeMap.values()
method is used to obtain the set of values present in the key-value pairs in the TreeMap
.
The syntax of the TreeMap.values()
method is shown below:
Collection<V> values();
The TreeMap.values()
method does not accept any parameters.
The TreeMap.values()
method returns a collection of values present in the key-value pairs in the TreeMap
.
Let’s have a look at the code.
import java.util.*;class Main{public static void main(String[] args){TreeMap<Integer, String> s = new TreeMap<Integer,String>();s.put(2,"Learn");s.put(12,"in-demand");s.put(31,"tech");s.put(18,"skills");s.put(25,"on");s.put(36,"Educative.io");System.out.println("TreeMap mappings are: "+ s);System.out.println("The values in the TreeMap are: " + s.values());}}
In line 1, we imported the required package.
In line 2, we made a Main
class.
In line 4, we made a main()
function.
In line 6, we declared a TreeMap
consisting of keys of type Integer
and values of type String
.
From lines 8 to 13, we inserted values in the TreeMap
using the TreeMap.put()
method.
In line 15, we displayed the mappings of the present in the TreeMap
.
In line 17, we used the TreeMap.values()
method to obtain the set of values present in the key-value pairs in the TreeMap
and displayed it.
So, this is how to use the TreeMap.values()
method in Java.