Java HashMap class implements Map interface using hastable (hash function), it inherits from AbstractMap class and implements Map interface
- Key-Pair: A HashMap containing key-based values.
- unique (unique): Only contain the key is unique, and can have duplicate values
- Null value: can have 1 null key and many null values
- Random order: remain unordered, so you should not access it by index. And the order may change over time.
- Not Thread Safe (not thread safe): Java HashMap is not thread safe, for multi-threaded environment you should use ConcurrentHashMap class to replace HashMap
- Constant Time: HashMap provides constant time for activities like get () and put () methods.
- Capacity: The default initial capacity of HashMap is 16
Create a HashMap
Below is the constructor of HashMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { /** * The default initial capacity - MUST be a power of two. */ static final int DEFAULT_INITIAL_CAPACITY = 16; /** * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; public HashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); } } |
Constructors of HashMap
HashMap has 4 types of constructors, these constuctors are designed to provide developer options
- HashMap has no parameters: it is the default constructor created as an instance of HashMap with an initial capacity of 16 and a load factor of 0.75.
1 2 | Map<K, V> basicHashMap = new HashMap(); |
- HashMap with the size parameter: This constructor HashMap creates a HashMap instance with a specified initial size and with a default load factor of 0.75.
1 2 | Map<K, V> basicHashMap = new HashMap(int initial capacity); |
- HashMap with parameters of capacity and load factor: This constructor creates a HashMap instance with the capacity and load factor that has been determined from the beginning.
1 2 | Map<K, V> basicHashMap = new HashMap(int initial capacity, float loadFactor); |
- HashMap with the parameter interface Map:
1 2 | Map<K, V> basicHashMap = new HashMap(Map map) |
HashMap methods in java
- boolean isEmpty ()
- Object put (Object key, Object value)
- int size ()
- get (Object key)
- void clear ()
- boolean containsKey (Object key)
- boolean containsValue (Object value)
- Object clone ()
- Set entrySet ()
- Set keySet ()
- Collection values ()
HashMap introduced methods in Java 8
- computeIfAbsent ()
- computeIfPresent
- compute
- forEach
- getOrDefault
- merge
- putIfAbsent
- remove
- replace
- boolean replace (K key, V oldValue, V newValue)
- replaceAll
Program example using HashMap
1 2 3 4 5 6 7 | public class CreateHashMapSample{ public static void main(String[] args) { // Create HashMap Map<String, String> hMap = new HashMap(); } } |
boolean isEmpty ()
Check if the map is empty or not? There are no key and value pairs, after running in this function will return true or false?
1 2 3 4 5 | // Create HashMap Map<String, String> hMap = new HashMap(); System.out.println("Member of the Map : "+hMap); System.out.println("Is Map empty : " + hMap.isEmpty()); |
Output of isEmpty ()
1 2 3 | Member of the Map : {} Is Map empty : true |
Object put (Object key, Object value)
Create a key with the corresponding value in HashMap, if the map contains the same key with different values, the old value will be replaced with the new value.
1 2 3 4 5 6 7 8 9 | Map<String, String> hMap = new HashMap(); System.out.println("Map before addition : "+hMap); // add new value hMap.put("microsoft", "Bing"); System.out.println("Map after addition of key-value: "+hMap); // update the value with sam key hMap.put("microsoft", "Operating System"); System.out.println("Map after replacement of key-value: "+hMap); |
The output of put ()
1 2 3 4 | Map before addition : {} Map after addition of key-value: {microsoft=Bing} Map after replacement of key-value: {microsoft=Operating System} |
get (Object key)
Returns a mapped value with the specified key and null if no map with any key
1 2 3 4 5 6 7 | Map<String, String> hMap = new HashMap(); // add new values hMap.put("microsoft", "Bing"); hMap.put("win10", "Operating System"); System.out.println("Get value of 'win10' from Map : " +hMap.get("win10")); |
Output of get () method
1 2 | Get value of 'win10' from Map : Operating System |
int size ()
Returns the number of key-value pairs in HashMap
1 2 3 4 5 6 7 8 9 10 11 | Map<String, String> hMap = new HashMap(); // add new values hMap.put("microsoft", "Bing"); System.out.println("Map members : "+hMap); System.out.println("Map size : "+hMap.size()); System.out.println(" *******Adding win10 (second entry)*******"); hMap.put("win10", "Operating System"); System.out.println("Map members : "+hMap); System.out.println("Map size : "+hMap.size()); |
Output of size ()
1 2 3 4 5 6 | Map members : {microsoft=Bing} Map size : 1 *******Adding win10 (second entry)******* Map members : {win10=Operating System, microsoft=Bing} Map size : 2 |
remove (Object key)
Delete the key along with its value
1 2 3 4 5 6 7 8 9 | Map<String, String> hMap = new HashMap(); // add new values hMap.put("microsoft", "Bing"); hMap.put("win10", "Operating System"); System.out.println("Map members : " +hMap); hMap.remove("win10"); System.out.println("Map members after removal of 'win10' : " +hMap); |
output after deleting the element
1 2 3 | Map members : {win10=Operating System, microsoft=Bing} Map members after removal of 'win10' : {microsoft=Bing} |
values ()
values () method returns all the values in Map
1 2 3 4 5 6 | Map<String, String> hMap = new HashMap(); hMap.put("aa", "bbbb"); hMap.put("larry", "Youtube"); System.out.println("Keys Presesnt in Map : " +hMap.keySet()); System.out.println("Values present in Map : " +hMap.values()); |
Output of keySet () and values ()
1 2 3 | Keys Presesnt in Map : [aa, larry] Values present in Map : [bbbb, Youtube] |
Display elements included in HashMap.
To display the elements included in HashMap, we have the following:
Use the for loop for improvement.
1 2 3 4 5 6 7 8 9 10 | public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("firstKey", "firstValue"); map.put("secondKey", "secondValue"); //enhanced for loop for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + " = " + entry.getValue()); } } |
output
1 2 3 | firstKey = firstValue secondKey = secondValue |
Also, from Java 8 onwards we can get all entries in HashMap using forEach () as follows:
1 2 3 4 5 6 7 8 9 | public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("firstKey", "firstValue"); map.put("secondKey", "SecondValue"); // for each with lambda map.forEach((key,value) -> System.out.println(key + " = " + value)); } |
Get the entire key of HashMap.
To get the entire key of HashMap, Java provides us with the keySet () method. This method will return 1 Set including the keys included in HashMap:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public static void main(String[] args) { HashMap<Integer, String> hashMap = new HashMap<>(); hashMap.put(2, "Thứ hai"); hashMap.put(3, "Thứ ba"); hashMap.put(4, "Thứ tư"); // phương thức keySet() // sẽ trả về 1 Set chứa key có trong hashMap System.out.println("Key của các entry trong hashMap: "); for (int key : hashMap.keySet()) { System.out.println("Key = " + key); } } |
output:
1 2 3 4 5 | key = 2 key = 3 key = 4 |
Get the entire value of HashMap.
To get the entire value of HashMap, Java provides us with the values () method. This method will return a collection of values included in HashMap:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public static void main(String[] args) { HashMap<String, String> hashMap = new HashMap<>(); hashMap.put("January", "Tháng 1"); hashMap.put("February", "Tháng 2"); hashMap.put("March", "Tháng 3"); // phương thức values() sẽ trả về // một tập hợp gồm các value có trong hashMap System.out.println("Các value có trong hashMap là: "); for (String value : hashMap.values()) { System.out.println("Value = " + value); } } |
output:
1 2 3 4 | value = Tháng 1 value = Tháng 2 value = Tháng 3 |
Refer to the article: https://chercher.tech/java/hashmap