CKTIS / Java
Map.values() — the map’s values view
`Map.values()` returns a collection backed by the map. Iterate over it to sum counters without looking up their keys or dropping repeated values.
Version: Java SE 21
Syntax
Collection<V> values();
// For an instance map of type Map<K, V>:
Collection<V> values = map.values();Map.values is shorthand for Map.values(), an instance method of java.util.Map<K, V>. Call it on a map with no arguments: map.values(). It returns a Collection<V> (V is the value type), with one element per mapping. Equal values under different keys appear more than once. Use keySet() for keys or entrySet() for key–value pairs.
This is a view, not a copy: adding, replacing, or removing a mapping in the map is visible through a view you already obtained. If removal is supported, values.remove(x) removes one matching mapping by value, not by key. Use map.remove(key) to target a particular key. The view does not support add or addAll. An unsupported modification can throw UnsupportedOperationException.
Do not assume an iteration order: HashMap guarantees none. A LinkedHashMap values view follows the map’s current encounter order. The no-argument constructor selects insertion order by default, but putFirst and putLast can reposition existing entries. Do not change the map while iterating over the view, except through that iterator’s own remove() if supported. Otherwise the general Map contract leaves the iteration result undefined.
When you only need the values, such as to sum four counters, a for-each loop is enough. If later map changes should not change which elements are in the collection, use new ArrayList<>(map.values()). This is a shallow copy: it does not clone the value objects.
Examples
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> counters = new HashMap<>();
counters.put("north", 4);
counters.put("south", 7);
counters.put("east", 4);
counters.put("west", 2);
Collection<Integer> values = counters.values();
System.out.println(sum(values));
counters.put("west", 5);
System.out.println(sum(values));
values.remove(7);
System.out.println(counters.containsKey("south"));
}
private static int sum(Collection<Integer> values) {
int total = 0;
for (int value : values) {
total += value;
}
return total;
}
}
Result
17 20 false
The first sum (`17`) includes both `4` values. After `west` changes from `2` to `5`, the same view gives `20`. `values.remove(7)` removes the `south` mapping, the only one with value `7`, so the key check prints `false`.
Related lessons
- Java · Lesson 58 · Basic · Version: 2
- Java · Lesson 39 · Intermediate · Version: 2