Skip to content

Java HashMap API

Java HashMap — hash-table-based implementation of the Map interface.

1 class · 10 methods

HashMap<K,V>

10 methods

Hash-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

NameTypeDescription
keyKKey.
valueVValue.

Returns

V

Example

java
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

NameTypeDescription
keyObjectKey to look up.

Returns

V

Example

java
Map<String, Integer> m = Map.of("a", 1);
m.get("a")  // 1
m.get("z")  // null
V remove(Object key)

Remove the mapping for key. Returns the previous value (or null).

Parameters

NameTypeDescription
keyObjectKey to remove.

Returns

V

Example

java
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

NameTypeDescription
keyObjectKey to check.

Returns

boolean

Example

java
Map<String, Integer> m = Map.of("a", 1);
m.containsKey("a")  // true
m.containsKey("z")  // false
boolean containsValue(Object value)

Return true if the map maps one or more keys to the specified value.

Parameters

NameTypeDescription
valueObjectValue to check.

Returns

boolean

Example

java
Map<String, Integer> m = Map.of("a", 1, "b", 2);
m.containsValue(2)  // true
m.containsValue(9)  // false
Set<K> keySet()

Return a Set view of the keys contained in the map.

Returns

Set<K>

Example

java
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

java
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

java
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

java
Map<String, Integer> m = Map.of("a", 1, "b", 2);
m.size()  // 2
boolean isEmpty()

Return true if the map contains no key-value mappings.

Returns

boolean

Example

java
new HashMap<>().isEmpty()  // true
Map.of("a", 1).isEmpty()    // false