The java.util.HashMap.values() method of HashMap class in Java is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the HashMap.
- Returns a Collection view backed by the HashMap, so changes in the map are reflected in the collection.
- Allows duplicate values, as HashMap values are not required to be unique.
- Commonly used for iterating, processing, and bulk operations on the values stored in the HashMap.
Example:
import java.util.HashMap;
public class GFG {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
map.put(3, "Java");
for (String value : map.values()) {
System.out.println(value);
}
}
}
Output
Java Python Java
Explanation: values() returns a collection containing all values of the HashMap.
Syntax
hashMap.values()
- Parameters: This method does not accept any parameters.
- Return Value: Returns a Collection containing all the values of the HashMap.
Mapping String values to Integer keys
This program demonstrates how the HashMap.values() method retrieves a collection view of all values stored in a HashMap.
import java.util.*;
public class GFG {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(10, "Geeks");
map.put(15, "for");
map.put(20, "Geeks");
map.put(25, "Welcomes");
map.put(30, "You");
// Using values() method
System.out.println("The collection is: " + map.values());
}
}
Output
The collection is: [Geeks, Welcomes, Geeks, You, for]
Explanation:
- Multiple key-value pairs are inserted using the put() method.
- values() method retrieves a collection containing all values present in the map.
Note: The values() method returns a collection view, not a separate copy.