Map.keySet()
Returns the set of all keys of a map.
Available since: Java 1.2
Syntax
Set<K> keySet()Return value
Set<K>A set of the keys, linked to the map.
Examples
The list of keys:
void main() {
Map<String, Integer> menu = new TreeMap<>(Map.of("soup", 5, "salad", 4, "cake", 3));
IO.println(menu.keySet());
for (String dish : menu.keySet()) {
IO.print(dish.toUpperCase() + " ");
}
IO.println("");
}Output:
[cake, salad, soup]
CAKE SALAD SOUPNotes
The key order is the map's order: unspecified for HashMap, sorted for TreeMap. You cannot add to keySet(), but removing from it removes the pair from the map. If you also need the values, iterate over entrySet().
See also
- Map.values() — Returns a collection of all values of a map.
- Map.entrySet() — Returns all key and value pairs for iteration.
- TreeMap — A map whose keys are always sorted.
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.