Java HashMap tutorial
last modified July 6, 2020
Java HashMap tutorial shows how to use Java HashMap collection.
Java HashMap
HashMap is a container that stores key-value pairs.
Each key is associated with one value. Keys in a HashMap
must
be unique. HashMap
is called an associative array or a dictionary in other programming
languages. HashMaps
take more memory because for each value there is also a key.
Deletion and insertion operations take constant time. HashMaps
can store null values.
HashMaps
do not maintain order.
Map.Entry represents a key-value pair in HashMap
.
HashMap's
entrySet()
returns a Set
view
of the mappings contained in the map. A set of keys is retrieved with the keySet()
method.
Java HashMap hierarchy
HashMap
extends AbstractMap
and implements Map
.
The Map
provides method signatures including get()
, put()
,
size()
, or isEmpty()
.
Java HashMap constructors
HashMap()
— constructs an emptyHashMap()
with the default initial capacity (16) and the default load factor (0.75).HashMap(int initialCapacity)
— constructs an emptyHashMap()
with the given initial capacity and the default load factor (0.75).HashMap(int initialCapacity, float loadFactor)
— constructs an emptyHashMap()
with the given initial capacity and load factor.HashMap(Map<? extends K,? extends V> m)
— constructs a newHashMap()
with the same mappings as the givenMap
.
K
is the type of the map keys and V
is the
type of mapped values.
Java HashMap methods
The following table provides a few HashMap
methods.
Modifier and type | Method | Description |
---|---|---|
void | clear() | Removes all mappings from the map. |
Object | clone() | Returns a shallow copy of the HashMap instance: the keys and values themselves are not cloned. |
V boolean | containsKey(Object key) | Returns true if this map contains a mapping for the specified key. |
Set<Map.Entry<K,V>> | entrySet() | Returns a Set view of the mappings contained in this map. |
boolean | isEmpty() | Returns true if this map is empty. |
Set<K> | keySet() | Returns a Set view of the keys contained in this map. |
V | put(K key, V value) | Adds new mapping to the map. |
V | remove(Object key) | Removes the mapping for the specified key from this map if present. |
V | get(Object key) | Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
void | forEach(BiConsumer<? super K,? super V> action) | Performs the given action for each entry in this map until all entries have been processed or the action throws an exception. |
V | replace(K key, V value) | Replaces the entry for the specified key only if it is currently mapped to some value. |
int | size() | Returns the number of key-value mappings in this map. |
Collection<V> | values() | Returns a Collection view of the values contained in this map. |
In this tutorial, we will work with several of these methods.
Java HashMap creation
HashMap
is created with new
keyword.
Map<String, String> capitals = new HashMap<>();
We specify the types of keys and values between angle brackets. Thanks to type inference, it is not necessary to provide types on the right side of the declaration.
Java HashMap put()
The put()
method is used to add a new mapping to
the map.
capitals.put("svk", "Bratislava");
The first parameter is the key, the second is the value.
Java HashMap remove()
The remove()
method is used to delete a pair from the map.
capitals.remove("pol");
The parameter is the key whose mapping is to be removed from the map.
Java HashMap initialization
Since Java 9, we have factory methods for HashMap
initialization.
package com.zetcode; import java.util.Map; import static java.util.Map.entry; // factory initialization methods since Java 9 public class HashMapInit { public static void main(String[] args) { // up to 10 elements: Map<Integer, String> colours = Map.of( 1, "red", 2, "blue", 3, "brown" ); System.out.println(colours); // any number of elements Map<String, String> countries = Map.ofEntries( entry("de", "Germany"), entry("sk", "Slovakia"), entry("ru", "Russia") ); System.out.println(countries); } }
The example uses Map.of
and Map.ofEntries
to initialize hashmaps. These two factory methods return unmodifiable
maps.
package com.zetcode; import java.util.HashMap; import java.util.Map; // up to Java 8 public class HashMapInit2 { public static void main(String[] args) { Map<String, String> countries = new HashMap<>() {{ put("de", "Germany"); put("sk", "Slovakia"); put("ru", "Russia"); }}; System.out.println(countries); } }
In this example we create a modifiable hashmap. This way of initialization is dubbed double-braced hashmap initialization.
Java HashMap size example
The size of the HashMap
is determined with the size()
method.
package com.zetcode; import java.util.HashMap; import java.util.Map; public class HashMapSize { public static void main(String[] args) { Map<String, String> capitals = new HashMap<>(); capitals.put("svk", "Bratislava"); capitals.put("ger", "Berlin"); capitals.put("hun", "Budapest"); capitals.put("czk", "Prague"); capitals.put("pol", "Warsaw"); capitals.put("ita", "Rome"); int size = capitals.size(); System.out.printf("The size of the HashMap is %d%n", size); capitals.remove("pol"); capitals.remove("ita"); size = capitals.size(); System.out.printf("The size of the HashMap is %d%n", size); } }
In the code example, we create a HashMap
and determine its
size with size()
. Then we remove some pairs and determine its
size again. We print the findings to the console.
capitals.put("svk", "Bratislava"); capitals.put("ger", "Berlin");
With put()
, we add new pairs into the HashMap
.
int size = capitals.size();
Here we get the size of the map.
capitals.remove("pol"); capitals.remove("ita");
With remove()
, we delete two pairs from the map.
The size of the HashMap is 6 The size of the HashMap is 4
This is the output of the example.
Java HashMap get()
To retrieve a value from a HashMap
, we use the get()
method.
It takes a key as a parameter.
package com.zetcode; import java.util.HashMap; import java.util.Map; public class HashMapRetrieve { public static void main(String[] args) { Map<String, String> capitals = new HashMap<>(); capitals.put("svk", "Bratislava"); capitals.put("ger", "Berlin"); capitals.put("hun", "Budapest"); capitals.put("czk", "Prague"); capitals.put("pol", "Warsaw"); capitals.put("ita", "Rome"); String cap1 = capitals.get("ita"); String cap2 = capitals.get("svk"); System.out.println(cap1); System.out.println(cap2); } }
In the example, we retrieve two values from the map.
String cap2 = capitals.get("svk");
Here we get a value which has "svk"
key.
Java HashMap clear()
The clear()
method removes all pairs from
the HashMap
.
package com.zetcode; import java.util.HashMap; import java.util.Map; public class HashMapClear { public static void main(String[] args) { Map<String, String> capitals = new HashMap<>(); capitals.put("svk", "Bratislava"); capitals.put("ger", "Berlin"); capitals.put("hun", "Budapest"); capitals.put("czk", "Prague"); capitals.put("pol", "Warsaw"); capitals.put("ita", "Rome"); capitals.clear(); if (capitals.isEmpty()) { System.out.println("The map is empty"); } else { System.out.println("The map is not empty"); } } }
In the example, we remove all elements and print the size of the map to the console.
capitals.clear();
We remove all pairs with clear()
.
if (capitals.isEmpty()) { System.out.println("The map is empty"); } else { System.out.println("The map is not empty"); }
With the isEmpty()
method, we check if the map
is empty.
Java HashMap containsKey()
The containsKey()
method returns true if the
map contains a mapping for the specified key.
package com.zetcode; import java.util.HashMap; import java.util.Map; public class HashMapContainsKey { public static void main(String[] args) { Map<String, String> capitals = new HashMap<>(); capitals.put("svk", "Bratislava"); capitals.put("ger", "Berlin"); capitals.put("hun", "Budapest"); capitals.put("czk", "Prague"); capitals.put("pol", "Warsaw"); capitals.put("ita", "Rome"); String key1 = "ger"; String key2 = "rus"; if (capitals.containsKey(key1)) { System.out.printf("HashMap contains %s key%n", key1); } else { System.out.printf("HashMap does not contain %s key%n", key1); } if (capitals.containsKey(key2)) { System.out.printf("HashMap contains %s key%n", key2); } else { System.out.printf("HashMap does not contain %s key%n", key2); } } }
In the example, we check if the map contains two keys.
if (capitals.containsKey(key1)) { System.out.printf("HashMap contains %s key%n", key1); } else { System.out.printf("HashMap does not contain %s key%n", key1); }
This if statement prints a message depending on whether the map contains the given key.
HashMap contains ger key HashMap does not contain rus key
This is the output.
Java HashMap replace()
There are replace()
methods which enable programmers to
replace entries.
replace(K key, V value)
This method replaces the entry for the specified key only if it is currently mapped to some value.
replace(K key, V oldValue, V newValue)
This method replaces the entry for the specified key only if it is currently mapped to the specified value.
package com.zetcode; import java.util.HashMap; import java.util.Map; public class HashMapReplace { public static void main(String[] args) { Map<String, String> capitals = new HashMap<>(); capitals.put("day", "Monday"); capitals.put("country", "Poland"); capitals.put("colour", "blue"); capitals.replace("day", "Sunday"); capitals.replace("country", "Russia", "Great Britain"); capitals.replace("colour", "blue", "green"); capitals.entrySet().forEach(System.out::println); } }
In the example, we replace pairs in the map with replace()
.
capitals.replace("day", "Sunday");
Here we replace a value for the "day"
key.
capitals.replace("country", "Russia", "Great Britain");
In this case, the value is not replaced because the key
is not currently set to "Russia"
.
capitals.replace("colour", "blue", "green");
Because the old value is correct, the value is replaced.
country=Poland colour=green day=Sunday
This is the output.
Java HashMap convert to List
In the next example we convert HashMap
entries to a list
of entries.
package com.zetcode; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public class HashMapConvert { public static void main(String[] args) { Map<String, String> colours = Map.of( "AliceBlue", "#f0f8ff", "GreenYellow", "#adff2f", "IndianRed", "#cd5c5c", "khaki", "#f0e68c" ); Set<Map.Entry<String, String>> entries = colours.entrySet(); List<Map.Entry<String, String>> mylist = new ArrayList<>(entries); System.out.println(mylist); } }
The entrySet()
returns a set view of mappings, which is later
passed to the constructor of the ArrayList
.
Java HashMap iteration with forEach()
We use Java 8 forEach()
method to iterate
over the key-value pairs of the HashMap
.
The forEach()
method performs the given action for each
element of the map until all elements have been processed
or the action throws an exception.
package com.zetcode; import java.util.HashMap; import java.util.Map; public class HashMapForEach { public static void main(String[] args) { Map<String, String> capitals = new HashMap<>(); capitals.put("svk", "Bratislava"); capitals.put("ger", "Berlin"); capitals.put("hun", "Budapest"); capitals.put("czk", "Prague"); capitals.put("pol", "Warsaw"); capitals.put("ita", "Rome"); capitals.forEach((k, v) -> System.out.format("%s: %s%n", k, v)); } }
In the code example, we iterate over a HashMap
with
forEach()
using a lambda expression.
capitals.forEach((k, v) -> System.out.format("%s: %s%n", k, v));
With forEach()
we iterate over all pairs of the map.
Java HashMap iteration with enhanced for loop
Enhanced for loop, introduced in Java 5, can be used to iterate
over a HashMap
.
package com.zetcode; import java.util.HashMap; import java.util.Map; public class HashMapEnhancedFor { public static void main(String[] args) { Map<String, String> capitals = new HashMap<>(); capitals.put("svk", "Bratislava"); capitals.put("ger", "Berlin"); capitals.put("hun", "Budapest"); capitals.put("czk", "Prague"); capitals.put("pol", "Warsaw"); capitals.put("ita", "Rome"); for (Map.Entry<String, String> pair: capitals.entrySet()) { System.out.format("%s: %s%n", pair.getKey(), pair.getValue()); } } }
In the example, we iterate over a HashMap
with enhanced for loop.
for (Map.Entry<String, String> pair: capitals.entrySet()) { System.out.format("%s: %s%n", pair.getKey(), pair.getValue()); }
In each for cycle, a new key-value couple is assigned to the pair
variable.
Java HashMap iteration over keys
We might want to iterate only over keys of a HashMap
.
package com.zetcode; import java.util.HashMap; import java.util.Map; import java.util.Set; public class HashMapKeys { public static void main(String[] args) { Map<String, String> capitals = new HashMap<>(); capitals.put("svk", "Bratislava"); capitals.put("ger", "Berlin"); capitals.put("hun", "Budapest"); capitals.put("czk", "Prague"); capitals.put("pol", "Warsaw"); capitals.put("ita", "Rome"); Set<String> keys = capitals.keySet(); keys.forEach(System.out::println); } }
The example iterates over keys of the capitals
map.
Set<String> keys = capitals.keySet();
The keys of a HashMap
are retrieved with the keySet()
method, which returns a Set
of keys. Keys must be unique; therefore,
we have a Set
. Set
is a collection that contains no
duplicate elements.
keys.forEach(System.out::println);
We go over the set of keys with forEach()
.
Java HashMap iteration over values
We might want to iterate only over values of a HashMap
.
package com.zetcode; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class HashMapValues { public static void main(String[] args) { Map<String, String> capitals = new HashMap<>(); capitals.put("svk", "Bratislava"); capitals.put("ger", "Berlin"); capitals.put("hun", "Budapest"); capitals.put("czk", "Prague"); capitals.put("pol", "Warsaw"); capitals.put("ita", "Rome"); Collection<String> vals = capitals.values(); vals.forEach(System.out::println); } }
The example iterates over values of a HashMap
.
Collection<String> vals = capitals.values();
The values of a HashMap
are retrieved with the values()
method.
vals.forEach(System.out::println);
We go over the collection with forEach()
.
HashMap filtering
HashMap
can be filtered with the filter()
method
of the Java Stream API.
package com.zetcode; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; public class HashMapFilter { public static void main(String[] args) { Map<String, String> capitals = new HashMap<>(); capitals.put("svk", "Bratislava"); capitals.put("ger", "Berlin"); capitals.put("hun", "Budapest"); capitals.put("czk", "Prague"); capitals.put("pol", "Warsaw"); capitals.put("ita", "Rome"); Map<String, String> filteredCapitals = capitals.entrySet().stream() .filter(map -> map.getValue().length() == 6) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); filteredCapitals.entrySet().forEach(System.out::println); } }
In the example, we filter the map to contain only pairs whose values' size is equal to six.
czk=Prague ger=Berlin pol=Warsaw
This is the output.
Java HashMap equivalents in other languages
Ruby has hashes, Perl has hashes, PHP has arrays, Python has dictionaries, C# has dictionaries, and JavaScript has maps.
#!/usr/bin/ruby stones = { 1 => "garnet", 2 => "topaz", 3 => "opal", 4 => "amethyst" } stones.each { |k, v| puts "Key: #{k}, Value: #{v}" }
This is a hash in Ruby.
#!/usr/bin/perl my %stones = ( 1 => "garnet", 2 => "topaz", 3 => "opal", 4 => "amethyst" ); while ( my ($k, $v) = each %stones ) { print "$k: $v\n"; }
This is a Perl hash.
<?php $stones = [ 1 => "garnet", 2 => "topaz", 3 => "opal", 4 => "amethyst" ]; foreach ($stones as $key => $value) { echo "$key: $value\n"; } ?>
This is a PHP array.
#!/usr/bin/python stones = { 1 : "garnet", 2 : "topaz", 3 : "opal", 4 : "amethyst" } for key, value in stones.items(): print("{}: {}".format(key, value))
This is a Python dictionary.
using System; using System.Collections.Generic; public class DictionaryExample { static void Main() { Dictionary<int, string> stones = new Dictionary<int, string> { { 1, "garnet" }, { 2, "topaz" }, { 3, "opal" }, { 4, "amethyst" }, }; Console.WriteLine("Keys and values of the dictionary:"); foreach(KeyValuePair<int, string> kvp in stones) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } } }
This is a C# dictionary.
var stones = new Map(); stones.set(1, 'garnet'); stones.set(2, 'topaz'); stones.set(3, 'opal'); stones.set(4, 'amethyst'); stones.forEach(function(value, key) { console.log(key + ': ' + value); });
This is a JavaScript map.
In this tutorial, we have presented the Java HashMap
collection.
List all Java tutorials.