{"id":7679,"date":"2025-05-28T14:55:17","date_gmt":"2025-05-28T14:55:17","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=7679"},"modified":"2026-04-01T11:48:03","modified_gmt":"2026-04-01T11:48:03","slug":"java-hashmap","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-hashmap\/","title":{"rendered":"HashMap &#8211; Java data structures"},"content":{"rendered":"<p>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.<\/p>\n<p>In this article, we will focus on one of the <a href=\"https:\/\/msgprogramator.sk\/en\/data-structures\/\">data structures<\/a>, the <strong>HashMap<\/strong> class, which allows the storage of key-value pairs and provides quick access to values based on keys.<\/p>\n<figure id=\"attachment_7559\" aria-describedby=\"caption-attachment-7559\" style=\"width: 1532px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-7558\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/HashMap-kolekcia-%E2%80%93-hierarchia-dedicnosti-min.webp\" alt=\"HashMap collection - inheritance hierarchy\" width=\"1532\" height=\"743\" \/><figcaption id=\"caption-attachment-7559\" class=\"wp-caption-text\">HashMap collection &#8211; inheritance hierarchy<\/figcaption><\/figure>\n<h2>HashMap in Java &#8211; data structure introduction<\/h2>\n<p><strong>The Java HashMap <\/strong>class is an implementation of the Map interface in the <em>java.util<\/em> 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 <em>null<\/em> values and <em>null<\/em> keys.<\/p>\n<p>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.<\/p>\n<div class=\"article-sharing-card\"><a href=\"https:\/\/msgprogramator.sk\/en\/java-hashtable\/\" class=\"article-card\"\n        aria-label=\"HashTable &#8211; Java data structures\"><div class=\"article-card-wrap\"><div class=\"article-card-wrap-image\"><span class=\"article-category\">Java<\/span><span class=\"article-reading-time\">9 min.<\/span><img loading=\"lazy\" decoding=\"async\" width=\"954\" height=\"600\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/hashtable-java-datove-struktury-954x600-1.webp\" class=\"img-fluid wp-post-image\" alt=\"HashTable - Java data structures\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/hashtable-java-datove-struktury-954x600-1.webp 954w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/hashtable-java-datove-struktury-954x600-1-300x189.webp 300w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/hashtable-java-datove-struktury-954x600-1-768x483.webp 768w\" sizes=\"auto, (max-width: 954px) 100vw, 954px\" \/><\/div><div class=\"article-wrap-content\"><div class=\"article-wrap-date\"><span class=\"article-date\">29. 5. 2025<\/span><\/div><h3 class=\"article-wrap-title\"><span href=\"https:\/\/msgprogramator.sk\/en\/java-hashtable\/\">HashTable &#8211; Java data structures<\/span><\/h3><div class=\"article-wrap-excerpt\">The HashTable class is a synchronized data structure for storing key-value pairs. Learn about its advantages, disadvantages and practical uses.                <\/div><\/div><\/div><\/a><\/div>\n<h2>HashMap &#8211; constructors<\/h2>\n<p>We have several constructors available to create a HashMap instance:<\/p>\n<p><strong>1. Empty HashMap with default capacity and load factor<\/strong><\/p>\n<p>Creates an empty HashMap with default initial capacity (16) and load factor (0.75).<\/p>\n<pre><code class=\"language-java\" data-line=\"\">HashMap&lt;K, V&gt; map = new HashMap&lt;&gt;();<\/code><\/pre>\n<p><strong>2. HashMap with a specified initial capacity<\/strong><\/p>\n<p>Creates an empty HashMap with the specified initial capacity and default load factor (0.75).<\/p>\n<pre><code class=\"language-java\" data-line=\"\">HashMap&lt;K, V&gt; map = new HashMap&lt;&gt;(int initialCapacity);<\/code><\/pre>\n<p><strong>3. HashMap with specified initial capacity and load factor<\/strong><\/p>\n<p>Creates an empty HashMap with the specified initial capacity and load factor.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">HashMap&lt;K, V&gt; map = new HashMap&lt;&gt;(int initialCapacity, float loadFactor);<\/code><\/pre>\n<p><strong>4. HashMap constructed from Map<\/strong><\/p>\n<p>Creates a new HashMap with the same mappings as the given Map.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">HashMap(Map&lt;? extends K,? extends V&gt; m)<\/code><\/pre>\n<h3>Initial capacity, Load Factor, Hash Function<\/h3>\n<p>These technical concepts related to creating a hash map have already been covered in the <a href=\"https:\/\/msgprogramator.sk\/en\/?p=7678\">HashTable<\/a> class, so I won&#8217;t repeat them here.<\/p>\n<h2>HashMap &#8211; basic operations<\/h2>\n<p>Some of the basic operations we can perform with HashMap include:<\/p>\n<ul>\n<li><strong>Inserting pairs: <\/strong><br \/>\nAdd a key-value pair using the <em>put(K key, V value)<\/em> method. If a new pair with the same key is inserted, the old value is overwritten by the new one.<\/li>\n<li><strong>Accessing values: <\/strong><br \/>\nGetting a value based on a key using the <em>get(Object key)<\/em> method.<\/li>\n<li><strong>Removing pairs: <\/strong><br \/>\nRemove a key-value pair using the <em>remove(Object key)<\/em> method.<\/li>\n<li><strong>Emptiness test: <\/strong><br \/>\nThe <em>isEmpty()<\/em> method tells us if the HashMap contains any pair at all.<\/li>\n<li><strong>Checking for the existence of a key or value: <\/strong><br \/>\nChecking for the presence of a value is done using the <em>containsValue(Object value)<\/em> method.<br \/>\nChecking for the presence of a key is done using the <em>containsKey(Object key)<\/em> method.<\/li>\n<li><strong>Finding the size: <\/strong><br \/>\nThe <em>size()<\/em> method returns the number of pairs in the table.<\/li>\n<li><strong>Clearing the table: <\/strong><br \/>\nThe <em>clear()<\/em> method removes all pairs from the table.<\/li>\n<li><strong>Iterating over pairs: <\/strong><br \/>\nUsing the <em>keySet()<\/em>, <em>values()<\/em> or <em>entrySet()<\/em> methods we can iterate over keys, values or entire pair.<\/li>\n<\/ul>\n<h2>Java HashMap documentation<\/h2>\n<p>For a complete overview of the HashMap class methods, see <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/23\/docs\/api\/java.base\/java\/util\/HashMap.html#method-summary\" target=\"_blank\" rel=\"nofollow noopener\">official documentation.<\/a><\/p>\n<h2>HashMap &#8211; advantages and disadvantages<\/h2>\n<h3>Disadvantages of HashMap<\/h3>\n<ul>\n<li><strong>Speed of operations: <\/strong><br \/>\nOperations such as put(), get(), and remove() have an average constant time complexity of O(1) due to the hashing mechanism.<\/li>\n<li><strong>Flexibility in using keys and values: <\/strong><br \/>\nYou can use any objects as a key and value, as long as the key implements the hashCode() and equals() methods.<\/li>\n<li><strong>Ease of use: <\/strong> The<br \/>\nAPI is clear and intuitive, making it easy to work with mapping data structures.<\/li>\n<\/ul>\n<h3>Disadvantages of HashMap<\/h3>\n<ul>\n<li><strong>Does not preserve the order of elements: <\/strong><br \/>\nHashMap does not guarantee the order of insertion, which can be a problem if it is important to maintain data consistency.<\/li>\n<\/ul>\n<div class=\"inside\"><\/div>\n<ul>\n<li><strong>Not synchronized: <\/strong><br \/>\nHashMap is not thread-safe, which means that conflicts can occur in a multi-threaded environment.<\/li>\n<\/ul>\n<div class=\"inside\"><\/div>\n<ul>\n<li><strong>Sensitivity to the implementation of hashCode and equals: <\/strong><br \/>\nIf the class we store as an element does not have the <em>hashCode()<\/em> and <em>equals()<\/em> methods implemented correctly, this can lead to unexpected behavior and performance degradation.<\/li>\n<li><strong>Performance in case of collisions: <\/strong><br \/>\nWhen 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.<\/li>\n<\/ul>\n<h2>HashMap &#8211; when to use it and when not to use it<\/h2>\n<p>The Java HashMap is suitable in the following situations:<\/p>\n<ul>\n<li>When you need fast, key-based access to data.<\/li>\n<li>If it is not necessary to maintain the order of the inserted elements.<\/li>\n<\/ul>\n<p>However, it is not suitable if we need to preserve the order of the inserted elements. In this case, LinkedHashMap is a better choice.<\/p>\n<h2>Example of using HashMap in Java<\/h2>\n<p><strong>HashMap<\/strong> 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.<\/p>\n<p>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.<\/p>\n<p><strong><u>VotingSystem.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import java.util.HashMap;\nimport java.util.Map;\nimport java.util.List;\nimport java.util.Arrays;\nimport java.util.Random;\n\npublic class VotingSystem {\n    public static void main(String[] args) {\n        \/\/ List of candidates\n        List&lt;String&gt; candidates = Arrays.asList(&quot;Alica&quot;, &quot;Beata&quot;, &quot;Cyril&quot;, &quot;Dominik&quot;, &quot;Jozef&quot;);\n\n        \/\/ Create a HashMap to store vote counts\n        HashMap&lt;String, Integer&gt; voteCounts = new HashMap&lt;&gt;();\n\n        \/\/ Run the voting simulation with N votes\n        int numberOfVotes = 1000;  \/\/ Change this number for different simulation sizes\n        voting(voteCounts, candidates, numberOfVotes);\n\n        \/\/ Display final election results\n        System.out.println(&quot;Election results:&quot;);\n        for (Map.Entry&lt;String, Integer&gt; entry : voteCounts.entrySet()) {\n            System.out.println(entry.getKey() + &quot;: &quot; + entry.getValue() + &quot; votes&quot;);\n        }\n    }\n\n    \/\/ Voting method that simulates N random votes\n    public static void voting(HashMap&lt;String, Integer&gt; voteCounts, List&lt;String&gt; candidates, int N) {\n        Random random = new Random();\n\n        for (int i = 0; i &lt; N; i++) {\n            \/\/ Randomly select a candidate from the list\n            String selectedCandidate = candidates.get(random.nextInt(candidates.size()));\n\n            \/\/ Add vote to the candidate in HashMap\n            voteCounts.put(selectedCandidate, voteCounts.getOrDefault(selectedCandidate, 0) + 1);\n        }\n    }\n}<\/code><\/pre>\n<p><strong>The output of this example is:<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-7604\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/hashmap-vystup-z-prikladu-min.jpg\" alt=\"HashMap - Output from the example \" width=\"297\" height=\"209\" \/><\/p>\n<p>We have prepared the files with the above example in the form of code that you can run directly in Java. Download the <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/05\/HashMap.zip\">Java code for <strong>HashMap<\/strong><\/a> here.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn about the HashMap data structure in Java &#8211; an overview of methods, operations, advantages, disadvantages and practical examples of its use.<\/p>\n","protected":false},"author":14,"featured_media":7565,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-7679","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java"],"acf":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/7679","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/comments?post=7679"}],"version-history":[{"count":2,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/7679\/revisions"}],"predecessor-version":[{"id":42899,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/7679\/revisions\/42899"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/7565"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=7679"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=7679"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=7679"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}