Map.values()
Returns a collection of all values of a map.
Available since: Java 1.2
Syntax
Collection<V> values()Return value
Collection<V>A collection of the values, linked to the map.
Examples
The sum of all values:
void main() {
Map<String, Integer> cart = Map.of("tea", 3, "milk", 2, "bread", 4);
int total = 0;
for (int qty : cart.values()) {
total += qty;
}
IO.println(total);
IO.println(cart.values().stream().mapToInt(Integer::intValue).max().getAsInt());
}Output:
9
4Notes
Values may repeat, so the result is a Collection rather than a Set. To get a separate modifiable list, copy it: new ArrayList<>(map.values()).
See also
- Map.keySet() — Returns the set of all keys of a map.
- Map.entrySet() — Returns all key and value pairs for iteration.
- IntStream.sum() — Adds up all numbers of a stream.
Related recipes
In the tutorial
- Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.