This blog post provides a comprehensive guide to Java HashMaps. It covers the fundamentals of HashMaps, including how they work and how to implement them in code. The post covers key topics such as put, get, and remove operations, collision and load factor, and iteration over a HashMap. The post also provides performance optimization techniques for Java HashMaps.
A Comprehensive Guide to Java HashMaps
What are Java HashMaps
HashMap is an implementation of Map interface. HashMaps store data in key-value pairs, where each key is associated with a specific value. When a user needs to retrieve a value, they provide the key, and the HashMap returns the corresponding value.
This is a Hash table based implementation of the Map interface.
The HashMap class is similar to Hashtable, except that it is unsynchronized and permits nulls
Implementing Java HashMaps in Your Code
For implementing a HashMap in your Java code, you’ll need to create an instance of the HashMap class.
You can then use the put() method to add key-value pairs to the HashMap, the get() method to retrieve values, and the remove() method to remove values.
Creating a HashMap
HashMap provides following constructors :
HashMap()
Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
HashMap(int initialCapacity)
Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).
HashMap(int initialCapacity, float loadFactor)
Constructs an empty HashMap with the specified initial capacity and load factor.
HashMap(Map m)
Constructs a new HashMap with the same mappings as the specified Map.
We can create a HashMap using the default constructor and add elements as follow :
Example:
HashMap<Integer,String> studentMap = new HashMap<>(); studentMap.put(1,"Ema"); studentMap.put(2, "John"); studentMap.put(3, "Chris");
We can also create a HashMap by passing its constructor another Map object.
Example:
HashMap<Integer,String> studentMap2 = new HashMap(studentMap);
Removing entries from HashMap
We can remove entries from HashMap using remove(key) or clear() methods.
remove() method
remove(key) removes the mapping for the key specified in parameter.
It returns the value associated with the key or null if key wasn’t found in map.
Following example explains this :
package com.topjavatutorial; import java.util.HashMap; public class HashMapDemo { public static void main(String[] args){ HashMap<Integer,String> studentMap = new HashMap<>(); studentMap.put(1,"Ema"); studentMap.put(2, "John"); System.out.println(studentMap.remove(2)); // prints John } }
clear() method
clear() method does not accept any parameters.
It removes all the entries from the HashMap and returns void.
HashMap<Integer,String> studentMap = new HashMap<>(); studentMap.put(1,"Ema"); studentMap.put(2, "John"); studentMap.clear();
Synchronizing Hashmap
HashMap is not synchronized.
A synchronized wrapper around the HashMap can be obtained using :
Map s = Collections.synchronizedMap(new HashMap(…));
HashMap keys
HashMap uses hashing functions to add or retrieve key-value pairs.
The key must override both methods equals() and hashCode() so that it can be added to a HashMap and retrieved from it.
The String class and all the wrapper classes override their hashCode() and equals() methods. So they can be correctly used as keys in a HashMap.
HashMap and Adding Duplicate Keys
If a key already exists in a HashMap and we try to add another value for the same key, then the old value of the key will be replaced with the new value.
Here is an example :
package com.topjavatutorial; import java.util.HashMap; public class HashMapDemo { public static void main(String[] args){ HashMap<Integer,String> studentMap = new HashMap<>(); studentMap.put(1,"Ema"); studentMap.put(1, "John"); System.out.println(studentMap.get(1)); // prints John } }
In the above example, we add an entry <1,"Ema"> and we added another entry >1,”John”>.
Since, the key is same, the value for 1 was replaced as “John”.
HashMap and Adding Null keys & values
HashMap accepts adding maximum 1 null key. Also, we can have null as a value.
package com.topjavatutorial; import java.util.HashMap; public class HashMapDemo { public static void main(String[] args){ HashMap<Integer,String> studentMap = new HashMap<>(); studentMap.put(null,"Ema"); studentMap.put(null, null); studentMap.put(null, "John"); System.out.println(studentMap.get(null)); // prints John } }
In above example, we tried adding 3 entries will null key, but only one remains and the value is the last value we provided.
Retrieving keys, value and key-value pairs in HashMap
keySet()
Keys in a HashMap can be retrievd using keySet() method.
It returns a Set object.
values()
Values in a HashMap can be retrieved using values() method.
It returns a Collection.
entrySet()
key-value pairs can be retrieved using entrySet() method.
It returns a Map.Entry object.
Here is an example :
package com.topjavatutorial; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class HashMapDemo { public static void main(String[] args){ HashMap<Integer,String> studentMap = new HashMap<>(); studentMap.put(1,"Ema"); studentMap.put(2, "John"); Set<Integer> keys = studentMap.keySet(); Collection<String> values = studentMap.values(); Set<Entry<Integer, String>> entries = studentMap.entrySet(); //prints keys for(Integer key:keys) System.out.println(key); //prints values for(String value:values) System.out.println(value); //prints key-value pairs for(Map.Entry entry : entries) System.out.println(entry.getKey() + " : " + entry.getValue()); } }
You may also like following articles on Java Collections:
- ConcurrentHashMap in Java
- TreeMap in java
- LinkedHashMap in java
- WeakHashMap in java
- IdentityHashMap in java
- HashSet in java
- LinkedList in java
- ArrayDeque in java
- ArrayList in java
© 2016 – 2023, https:. All rights reserved. On republishing this post, you must provide link to original post
[…] value for the same key, then the old value of the key will be replaced with the new value. Read more about HashMap […]
[…] HashMap in java […]