HashMap values() Method in Java

Published by user on

The values() method of HashMap returns a collection of the values in this map. Returned collection is backed by the map. This means if the map changes then the returned collection changes. Similarly, if the retuned collection changed then the map changes.

Syntax

Collection values()

Parameters

It does not take any parameter

Return Type/Value

It returns a collection of the values in this map.

Program

import java.util.HashMap;
import java.util.Map;

public class HashMapValuesExample {

    public static void main(String[] args) {

        Map < Integer, String > map = new HashMap < > ();
        map.put(101, "John");
        map.put(102, "Adam");
        map.put(103, "Ricky");
        map.put(104, "Chris");
        map.put(105, null);

        System.out.println("Map elements: " + map);
        System.out.println("Values in the map: " + map.values());
    }
}

Output

Map elements: {101=John, 102=Adam, 103=Ricky, 104=Chris, 105=null}
Values in the map: [John, Adam, Ricky, Chris, null]

Explanation

  • Create a new HashMap
  • Add keys and values to it
  • Get all the values in the HashMap using the values() method
  • The call to the method returned the snapshot of all the values including null
Categories: Java