What is the values() method of the HashMap class in Java?

The values() method of the HashMap class in Java returns a Collection view of the values present in a HashMap instance.

The process is illustrated below:

To use the values() method, you will need to import the HashMap class into the program, as shown below:

import java.util.HashMap;

The prototype of the values() method is shown below:

public Collection<V> values()

Parameters

The values() method does not take any parameters.

Return value

The values() method returns a Collection view of the values present in a HashMap instance.

If there are duplicate values in the HashMap, they are all returned as part of the view.

Example

The code below shows how the values() method works in Java:

import java.util.HashMap;
class Main {
public static void main(String[] args)
{
// initializing HashMap
HashMap<String, Integer> vehicles = new HashMap<>();
// populating HashMap
vehicles.put("Car", 1);
vehicles.put("Bus", 2);
vehicles.put("Truck", 3);
vehicles.put("Bike", 1);
// view all values in the HashMap
System.out.println("The HashMap contains the following values: " + vehicles.values());
}
}

Explanation

First, a HashMap object vehicles is initialized.

Next, key-value pairs are inserted into the HashMap. The value 11 is used for two entries: “Car” and “Bike”. All other entries have unique values.

The values method in line 1616 proceeds to return a Collection view of all the values in the HashMap. The HashMap contains a duplicate for the value 11, so the view contains two occurrences of the value 11.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved