Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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
4

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.