The values() method of the Map interface returns a Collection view of all values stored in the map. The returned collection is backed by the map, meaning any modification to the map is immediately reflected in the collection and vice versa. Also, it does not support adding elements directly.
Example:
import java.util.HashMap;
import java.util.Map;
class GFG {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
System.out.println(map.values());
}
}
Output
[Java, Python]
Explanation:
- map.put() inserts key–value pairs into the HashMap.
- map.values() returns a Collection view containing all values present in the map.
Syntax:
map.values()
- Parameter: This method does not take any parameter.
- Return value: It returns a collection view of all the values present in the map.
Example 1. Retrieving All Values from a Map
This code depicts the way values() returns a collection containing all values stored in a HashMap.
import java.util.*;
public class GfG {
public static void main(String[] args){
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(12345, "student 1");
map.put(22345, "student 2");
map.put(323456, "student 3");
map.put(32496, "student 4");
map.put(32446, "student 5");
map.put(32456, "student 6");
System.out.println(map.values());
}
}
Output
[student 4, student 3, student 6, student 1, student 2, student 5]
Explanation:
- map.values() returns a collection containing all values in the map.
- Since HashMap does not maintain insertion order, the output order may vary.
- The returned collection is directly linked to the map.
Example 2. Demonstrating Backed Collection Behavior
The changes made to the map are automatically reflected in the collection returned by values(). Below given code proves the same.
import java.util.*;
public class GfG {
public static void main(String[] args){
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(12345, "student 1");
map.put(22345, "student 2");
map.put(323456, "student 3");
Collection<String> collectionValues = map.values();
System.out.println("Before modification\n");
for(String s: collectionValues){
System.out.println(s);
}
map.put(3245596, "student 7");
System.out.println("\nAfter modification\n");
for(String s: collectionValues){
System.out.println(s);
}
}
}
Output
Before modification student 3 student 1 student 2 After modification student 3 student 1 student 2 student 7
Explanation:
- The collection values is backed by the map.
- Adding "student 7" to the map automatically updates the collection.
- No separate update is required for the collection view.
Note: The returned collection does not support add() operation. Calling add() on the values collection throws UnsupportedOperationException.