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()
The values()
method does not take any parameters.
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.
The code below shows how the values()
method works in Java:
import java.util.HashMap;class Main {public static void main(String[] args){// initializing HashMapHashMap<String, Integer> vehicles = new HashMap<>();// populating HashMapvehicles.put("Car", 1);vehicles.put("Bus", 2);vehicles.put("Truck", 3);vehicles.put("Bike", 1);// view all values in the HashMapSystem.out.println("The HashMap contains the following values: " + vehicles.values());}}
First, a HashMap
object vehicles
is initialized.
Next, key-value pairs are inserted into the HashMap
. The value is used for two entries: “Car” and “Bike”. All other entries have unique values.
The values
method in line proceeds to return a Collection
view of all the values in the HashMap
. The HashMap
contains a duplicate for the value , so the view contains two occurrences of the value .
Free Resources