Java HashMap is an unordered key-value pair mappings collection, implementation of java.util.Map interface. HashMap has the following attributes

  • Backed by hash table data structure

  • No guarantees to the iteration order

  • No duplicate keys. Permits null key and null value

  • Offers constant time performance for get and put operations, assuming the hash function distributes the elements properly among the buckets

  • Unsynchronized implementation. In multi-threading environment with at least one thread modifies the list, it must be synchronized externally

HashMap declaration and initialization

with HashMap's constructors

  • Create a new empty HashMap
Map<String, Integer> map = new HashMap<>();  
  • Create a new HashMap with the same mappings as the specified map
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
System.out.println(map); // {k1=1}

Map<String, Integer> map2 = new HashMap<>(map);  
System.out.println(map2); // {k1=1}  
  • Create and init a map in one line with double brace initialization (should not be used)
Map<String, Integer> map = new HashMap<>(){{  
   put("k1", 1);
   put("k2", 2);
}};

Double brace initialization can lead to memory leaks as it creates an anonymous class with a reference to the owner object

  • Create and init a map in multiple lines
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", 2);  


with Collections class

  • Create a new empty unmodifiable map with Collections.emptyMap()
Map<String, Integer> immutableMap = Collections.emptyMap();  
  • Create and init a single key-value unmodifiable map in one line with Collections.singletonMap(K key, V value)
Map<String, Integer> immutableMap = Collections.singletonMap("k1", 1);  


with Java 9+

Using Map.of, Map.ofEntries and Map.copyOf factory methods to create and init an unmodifiable map in one line.

UnsupportedOperationException will be thrown if attempting to add, remove or update keys and values

NullPointerException will be thrown if attempting to create with null keys or values

IllegalArgumentException will be thrown if attempting to create with duplicate keys

  • with Map.of(...)
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
  • with Map.ofEntries(...)
Map<String, Integer> immutableMap = Map.ofEntries(Map.entry("k1", 1), Map.entry("k2", 2));  
  • with Map.copyOf(...)
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", 2);

Map<String, Integer> immutableMap = Map.copyOf(map);  
System.out.println(immutableMap); // {k2=2, k1=1}

HashMap traversal

Iterate over key-value pairs

  • with forEach(BiConsumer<? super K, ? super V> action) of Map interface, since Java 8+
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
immutableMap.forEach((k, v) -> System.out.printf("%s=%d%s", k, v, System.lineSeparator()));  


Iterate over HashMap's entrySet()

  • with for-each loop
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
for (Map.Entry<String, Integer> entry : immutableMap.entrySet()) {  
   System.out.println(entry);
}
  • with forEach(Consumer<? super T> action) of Iterable interface, since Java 8+
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
immutableMap.entrySet().forEach(System.out::println);  


Iterate over HashMap's keySet()

  • with for-each loop
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
for (String key : immutableMap.keySet()) {  
   System.out.println(key);           
}
  • with forEach(Consumer<? super T> action) of Iterable interface, since Java 8+
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
immutableMap.keySet().forEach(System.out::println);  


Iterate over HashMap's values()

  • with for-each loop
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
for (Integer value : immutableMap.values()) {  
   System.out.println(value);           
}
  • with forEach(Consumer<? super T> action) of Iterable interface, since Java 8+
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
immutableMap.values().forEach(System.out::println);  

Query operations

get operations

  • V get(Object key) gets the value mapped to the key argument

    The returned value may be null if the key is mapped to null or there is no mapping value to it

Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);

map.get("k1"); // 1  
map.get("k2"); // null  
map.get("k3"); // null  
map.get(null); // null
  • V getOrDefault(Object key, V defaultValue) gets the value mapped to the key argument or defaultValue if there is no mappings for the key
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);

map.get("k1", 0); // 1  
map.get("k3", 0); // 0


containsKey and containsValue operations

  • boolean containsKey(Object key) checks if a map contains a mapping for the specified key
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);

System.out.println(map.containsKey("k1")); // true  
System.out.println(map.containsKey("k3")); // false  
  • boolean containsValue(Object value) checks if a map contains a mapping for the specified value
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);

System.out.println(map.containsValue(1)); // true  
System.out.println(map.containsValue(2)); // false  


size and isEmpty operations

  • int size() gets the number of key-value mappings in a map, O(1)
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
map.size(); // 2
  • boolean isEmpty() checks if a map contains no key-value mappings, O(1)
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
map.isEmpty(); // false

Modification operations

put operations

  • V put(K key, V value) puts the key-value mapping to a map. If key is existed, old value is replaced by the specified value
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);  
System.out.println(map); // {k1=1, k2=null}

map.put("k2", 2);  
System.out.println(map); // {k1=1, k2=2}
  • V putIfAbsent(K key, V value) puts the key-value mapping to a map either there's no associated or the key is associated with null. If there's an associated, return the current value
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);  
System.out.println(map); // {k1=1, k2=null}

map.putIfAbsent("k3", 3);  
map.putIfAbsent("k1", 4);  
map.putIfAbsent("k2", 2);  
System.out.println(map); // {k1=1, k2=2, k3=3}
  • void putAll(Map<? extends K, ? extends V> m) copies all mappings from the specified map
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);  
System.out.println(map); // {k1=1, k2=null}

Map<String, Integer> map2 = new HashMap<>();  
map2.put("k3", 3);  
map2.putAll(map);  
System.out.println(map2); // {k1=1, k2=null, k3=3}  


replace operations

  • V replace(K key, V value) replaces the old value to the specified value if the specified key is existed in map
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);  
System.out.println(map); // {k1=1, k2=null}

map.replace("k2", 2);  
map.replace("k3", 3); // {k1=1, k2=2}  
  • boolean replace(K key, V oldValue, V newValue) replaces the specified oldValue to the specified newValue if the specified key is currently associated with oldValue in map
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);  
System.out.println(map); // {k1=1, k2=null}

map.replace("k1", 1, 10);  
map.replace("k2", 2, 20); // {k1=10, k2=null}  
  • void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) replaces all current values to the value returned by the function argument
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);  
System.out.println(map); // {k1=1, k2=null}

map.replaceAll((k, v) -> 100)  
System.out.println(map); // {k1=100, k2=100}  


remove and clear operations

  • V remove(Object key) removes the entry by the specified key
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);  
System.out.println(map); // {k1=1, k2=null}

map.remove("k2");  
map.remove("k3");  
System.out.println(map); // {k1=1}  
  • boolean remove(Object key, Object value) removes the entry by the specified key and value
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);  
System.out.println(map); // {k1=1, k2=null}

map.remove("k1", 10);  
map.remove("k2", null);  
System.out.println(map); // {k1=1}  
  • void clear() removes all mapping entries from map
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);  
System.out.println(map); // {k1=1, k2=null}

map.clear();  
System.out.println(map); // {}