Java TreeMap values() Method Example

The values() method of java.util.TreeMap class returns a Collection view of the values contained in this map. The collection’s iterator returns the values in ascending order of the corresponding keys.

Signature

public Collection<V> values()

This method returns a Collection view of the values contained in this map. The collection’s iterator returns the values in ascending order of the corresponding keys.

Example

The following example shows the usage of java.util.TreeMap.values() method.

import java.util.Collection;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class ValuesMethodTreeMapExample 
{
    public static void main(String args[])
    {
        // create an empty TreeMap
        TreeMap<Integer,String>  treeMap1 = new TreeMap<Integer,String>();
        SortedMap<Integer, String>  subMap = new TreeMap<Integer,String>();
        
        // use put() method to put elements to the TreeMap
        treeMap1.put(1,"Element1");
        treeMap1.put(2,"Element2");
        treeMap1.put(3,"Element3");
        treeMap1.put(4,"Element4");
        treeMap1.put(5,"Element5");
        
        //Print the elements of TreeMap 
        System.out.println("**Elements of TreeMap**");
        for(Map.Entry<Integer,String> entry : treeMap1.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" ...."+"Value : "+entry.getValue());
        }
        
        //Get the values alone from the treeMap
        Collection collection = treeMap1.values();
        //Print the values of the treeMap(collection) 
        System.out.println("**Values of the TreeMap**");
        System.out.println(collection);
     }
}

Output

**Elements of TreeMap**
Key : 1 ....Value : Element1
Key : 2 ....Value : Element2
Key : 3 ....Value : Element3
Key : 4 ....Value : Element4
Key : 5 ....Value : Element5
**Values of the TreeMap**
[Element1, Element2, Element3, Element4, Element5]

Leave a Reply

Your email address will not be published. Required fields are marked *