Java HashMap values() Method Example

The values() method of java.util.HashMap class returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.

Signature

public Collection<V> values()

This method returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress the results of the iteration are undefined.

Example

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

import java.util.HashMap;

public class ValuesMethodHashMapExample 
{
    public static void main(String args[])
    {
        // create an empty HashMap
        HashMap<Integer,String> hashMap1 = new HashMap<Integer,String>();
        
        // use put() method to put elements to the HashMap1
        hashMap1.put(1,"Element1");
        hashMap1.put(2,"Element2");
        hashMap1.put(3,"Element3");
        hashMap1.put(4,"Element4");
        hashMap1.put(5,"Element5");
        
        //lets print the values of the hashMap1
        System.out.println("Values of the hashMap1 are : "+hashMap1.values());
    }
}

Output

Values of the hashMap1 are : [Element1, Element2, Element3, Element4, Element5]

Leave a Reply

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