HashMap<K,V>
10 methodsHash-table-based implementation of the Map interface. Permits null keys and values.
V put(K key, V value)Associate value with key. Returns the previous value (or null).
Parameters
| Name | Type | Description |
|---|---|---|
| key | K | Key. |
| value | V | Value. |
Returns
V
Example
Map<String, Integer> m = new HashMap<>();
m.put("a", 1);
m.put("a", 2); // returns 1, m == {"a": 2}V get(Object key)Return the value to which key is mapped, or null if not present.
Parameters
| Name | Type | Description |
|---|---|---|
| key | Object | Key to look up. |
Returns
V
Example
Map<String, Integer> m = Map.of("a", 1);
m.get("a") // 1
m.get("z") // nullV remove(Object key)Remove the mapping for key. Returns the previous value (or null).
Parameters
| Name | Type | Description |
|---|---|---|
| key | Object | Key to remove. |
Returns
V
Example
Map<String, Integer> m = new HashMap<>(Map.of("a", 1));
Integer old = m.remove("a");
// old == 1, m == {}boolean containsKey(Object key)Return true if the map contains a mapping for the specified key.
Parameters
| Name | Type | Description |
|---|---|---|
| key | Object | Key to check. |
Returns
boolean
Example
Map<String, Integer> m = Map.of("a", 1);
m.containsKey("a") // true
m.containsKey("z") // falseboolean containsValue(Object value)Return true if the map maps one or more keys to the specified value.
Parameters
| Name | Type | Description |
|---|---|---|
| value | Object | Value to check. |
Returns
boolean
Example
Map<String, Integer> m = Map.of("a", 1, "b", 2);
m.containsValue(2) // true
m.containsValue(9) // falseSet<K> keySet()Return a Set view of the keys contained in the map.
Returns
Set<K>
Example
Map<String, Integer> m = Map.of("a", 1, "b", 2);
m.keySet() // ["a", "b"] (order not guaranteed)Collection<V> values()Return a Collection view of the values contained in the map.
Returns
Collection<V>
Example
Map<String, Integer> m = Map.of("a", 1, "b", 2);
m.values() // [1, 2] (order not guaranteed)Set<Map.Entry<K,V>> entrySet()Return a Set view of the mappings contained in the map.
Returns
Set<Map.Entry<K,V>>
Example
Map<String, Integer> m = Map.of("a", 1, "b", 2);
for (Map.Entry<String, Integer> e : m.entrySet()) {
System.out.println(e.getKey() + "=" + e.getValue());
}int size()Return the number of key-value mappings in the map.
Returns
int
Example
Map<String, Integer> m = Map.of("a", 1, "b", 2);
m.size() // 2boolean isEmpty()Return true if the map contains no key-value mappings.
Returns
boolean
Example
new HashMap<>().isEmpty() // true
Map.of("a", 1).isEmpty() // false