HashMap – Java data structures
Java HashMap is one of a number of data structures for efficient data handling. In our series, we will introduce various other collections in turn. We will show how to work with them, what operations can be done with them or which methods are most commonly used. We will also mention their advantages and disadvantages and when it is appropriate to use a particular data structure.

V článku sa dozvieš:
In this article, we will focus on one of the data structures, the HashMap class, which allows the storage of key-value pairs and provides quick access to values based on keys.

HashMap in Java – data structure introduction
The Java HashMap class is an implementation of the Map interface in the java.util package. It allows the storage of key-value pairs, where each key is unique and maps to a specific value. This implementation provides all optional map operations and allows null values and null keys.
The HashMap class is roughly equivalent to the Hashtable class, except that HashMap is unsynchronized and allows null values. HashMap uses a hash table to store elements, providing fast lookup, insertion, and removal of elements with an average time complexity of O(1). It is important to note that HashMap does not maintain the order of the inserted elements.
HashMap – constructors
We have several constructors available to create a HashMap instance:
1. Empty HashMap with default capacity and load factor
Creates an empty HashMap with default initial capacity (16) and load factor (0.75).
HashMap<K, V> map = new HashMap<>();
2. HashMap with a specified initial capacity
Creates an empty HashMap with the specified initial capacity and default load factor (0.75).
HashMap<K, V> map = new HashMap<>(int initialCapacity);
3. HashMap with specified initial capacity and load factor
Creates an empty HashMap with the specified initial capacity and load factor.
HashMap<K, V> map = new HashMap<>(int initialCapacity, float loadFactor);
4. HashMap constructed from Map
Creates a new HashMap with the same mappings as the given Map.
HashMap(Map<? extends K,? extends V> m)
Initial capacity, Load Factor, Hash Function
These technical concepts related to creating a hash map have already been covered in the HashTable class, so I won’t repeat them here.
HashMap – basic operations
Some of the basic operations we can perform with HashMap include:
- Inserting pairs:
Add a key-value pair using the put(K key, V value) method. If a new pair with the same key is inserted, the old value is overwritten by the new one. - Accessing values:
Getting a value based on a key using the get(Object key) method. - Removing pairs:
Remove a key-value pair using the remove(Object key) method. - Emptiness test:
The isEmpty() method tells us if the HashMap contains any pair at all. - Checking for the existence of a key or value:
Checking for the presence of a value is done using the containsValue(Object value) method.
Checking for the presence of a key is done using the containsKey(Object key) method. - Finding the size:
The size() method returns the number of pairs in the table. - Clearing the table:
The clear() method removes all pairs from the table. - Iterating over pairs:
Using the keySet(), values() or entrySet() methods we can iterate over keys, values or entire pair.
Java HashMap documentation
For a complete overview of the HashMap class methods, see official documentation.
HashMap – advantages and disadvantages
Disadvantages of HashMap
- Speed of operations:
Operations such as put(), get(), and remove() have an average constant time complexity of O(1) due to the hashing mechanism. - Flexibility in using keys and values:
You can use any objects as a key and value, as long as the key implements the hashCode() and equals() methods. - Ease of use: The
API is clear and intuitive, making it easy to work with mapping data structures.
Disadvantages of HashMap
- Does not preserve the order of elements:
HashMap does not guarantee the order of insertion, which can be a problem if it is important to maintain data consistency.
- Not synchronized:
HashMap is not thread-safe, which means that conflicts can occur in a multi-threaded environment.
- Sensitivity to the implementation of hashCode and equals:
If the class we store as an element does not have the hashCode() and equals() methods implemented correctly, this can lead to unexpected behavior and performance degradation. - Performance in case of collisions:
When there are a large number of collisions (when multiple elements have the same hash code), performance may be degraded because operations may behave more slowly.
HashMap – when to use it and when not to use it
The Java HashMap is suitable in the following situations:
- When you need fast, key-based access to data.
- If it is not necessary to maintain the order of the inserted elements.
However, it is not suitable if we need to preserve the order of the inserted elements. In this case, LinkedHashMap is a better choice.
Example of using HashMap in Java
HashMap excels at efficiently storing key-value pairs and retrieving them quickly thanks to a hashing method when we need to retrieve and use them. herefore, HashMap has a wide range of applications.
We illustrate the use of the HashMap collection with the example of elections. We will define a list of candidates and use the voting() method to simulate a secret ballot. We will use the HashMap data structure to count the votes, where the key will be the name of the candidate and the value will be the current number of votes. Finally, we list the number of votes for each candidate.
VotingSystem.java
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Arrays;
import java.util.Random;
public class VotingSystem {
public static void main(String[] args) {
// List of candidates
List<String> candidates = Arrays.asList("Alica", "Beata", "Cyril", "Dominik", "Jozef");
// Create a HashMap to store vote counts
HashMap<String, Integer> voteCounts = new HashMap<>();
// Run the voting simulation with N votes
int numberOfVotes = 1000; // Change this number for different simulation sizes
voting(voteCounts, candidates, numberOfVotes);
// Display final election results
System.out.println("Election results:");
for (Map.Entry<String, Integer> entry : voteCounts.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue() + " votes");
}
}
// Voting method that simulates N random votes
public static void voting(HashMap<String, Integer> voteCounts, List<String> candidates, int N) {
Random random = new Random();
for (int i = 0; i < N; i++) {
// Randomly select a candidate from the list
String selectedCandidate = candidates.get(random.nextInt(candidates.size()));
// Add vote to the candidate in HashMap
voteCounts.put(selectedCandidate, voteCounts.getOrDefault(selectedCandidate, 0) + 1);
}
}
}
The output of this example is:

We have prepared the files with the above example in the form of code that you can run directly in Java. Download the Java code for HashMap here.

