HashMap in java



In this Collection framework tutorial we will learn what is java.util.HashMap in Collection framework in java.


Contents of page :


1) java.util.HashMap in java
java.util.HashMap is implementation of the java.util.Map interface.
java.util.HashMap enables us to store data in key-value pair form. Insertion order of key-value pairs is not maintained.
In an HashMap, two keys k1 and k2 are equal if and only if (k1==null ? k2==null : k1.equals(k2))


2) Understanding (k1==null ? k2==null : k1.equals(k2)) >
If k1 is null, check k2==null, if k2 is also null then k1 and k2 are equal else they are not equal.
If k1 is not null, check  k1.equals(k2), if equals return true than k1 and k2 are equal else they are not equal.


Must read :  HashMap Custom implementation in java

3) What is hierarchy of HashMap in java?
-java.lang.Object
-java.util.AbstractMap
 -java.util.concurrent.HashMap


For more detailed hierarchy information read : Map hierarchy in java


4) Creating java.util.HashMap (using constructor)
Constructs a new HashMap, Its initial capacity is 16. And load factor is 0.75 (We’ll discuss it later in post)
Map<Integer,String> hashMap=new HashMap<Integer,String>();
Defining HashMap<Integer,String> means key can of Integer type and value can be String type only, using any other type will cause compilation error in java.


5) put element in java.util.HashMap
put(K key, V value)
Method allows you put specified key-value pair in HashMap. If the map already contains a mapping for the key, the old value is replaced in java.
hashMap.put(11, "javaMadeSoEasy");

6) get elements from java.util.HashMap
get(Object key)
Method returns value corresponding to key.
Method returns null if map does not contain key.


hashMap.get(2);
Method returns element on 2nd index in java.
         
7) containsKey method in HashMap
containsKey(Object key)
Method returns true if map contains a mapping for the specified key in java.
hashMap.containsKey(2);


8) containsValue method in HashMap
containsValue(Object value)
Method returns true if map maps one or more keys to the specified value in java.
hashMap.containsKey(2);


9) Remove element from HashMap
remove(Object key)
Method removes specified key-value pair from HashMap and returns value corresponding to specified key.
hashMap.remove(11);


         
10) Size of HashMap in java
size()
Method returns size of HashMap in java.


System.out.println(hashMap.size());
will print size of hashMap.

11) Iterate over java.util.HashMap >
Before iterating we will put 3 key-value pairs in hashMap.
      hashMap.put(11, "javaMadeSoEasy");
   hashMap.put(21, "bmw");
   hashMap.put(31, "ferrari");


11.1) Iterate over keys -
hashMap.keySet().iterator() method returns iterator to iterate over keys in HashMap.


Iterator<Integer> keyIterator=hashMap.keySet().iterator();
while(keyIterator.hasNext()){
 System.out.println(keyIterator.next());
}

/*OUTPUT
21
11
31
*/


Iteration using enhanced for loop in java.
hashMap.keySet() returns set of keys.
Set<Integer> keySet=hashMap.keySet();
for(Integer key :keySet){
 System.out.println(key);
}    


iterator returned is fail fast in java. Means any structural modification made to HashMap like adding or removing elements during Iteration will throw java.util.ConcurrentModificationException.
Few more important points about iterator >
  • Removing element by using iterator may throw IllegalStateException
  • If we add some key which is already present in set than no exception is thrown because size of map remains same (it is not structural modification ).


Iterator<String> iterator=hashMap.iterator();
while(iterator.hasNext()){
 System.out.println(iterator.next());
 hashMap.put(4, "d");
}
key-value has been added (map didn’t contained this key previously) during iteration which cause ConcurrentModificationException to be thrown.

11.2) Iterate over values in java -
hashMap.values().iterator() method returns iterator to iterate over keys in HashMap in java.


Iterator<String> valueIterator=hashMap.values().iterator();
while(valueIterator.hasNext()){
 System.out.println(valueIterator.next());
}

/*OUTPUT
javaMadeSoEasy
audi
ferrari
*/


Iteration using enhanced for loop in java.
hashMap.values() returns collection of values.
Collection<String> collection=hashMap.values();
for(String value :collection){
 System.out.println(value);
}


iterator returned is fail fast. Means any structural modification made to HashMap like adding or removing elements during Iteration will throw java.util.ConcurrentModificationException.
Few more important points about iterator >
  • Removing element by using iterator may throw IllegalStateException
  • If we add some key which is already present in set than no exception is thrown because size of map remains same (it is not structural modification ).


Iterator<String> iterator=hashMap.iterator();
while(iterator.hasNext()){
 System.out.println(iterator.next());
 hashMap.put(4, "d");
}
key-value has been added (map didn’t contained this key previously) during iteration which cause ConcurrentModificationException to be thrown.

11.3) Iterate over Entry in java-
hashMap.entrySet().iterator() method returns iterator to iterate over keys in HashMap.


Iterator<Entry<Integer, String>> entryIterator=hashMap.entrySet().iterator();
while(entryIterator.hasNext()){
   System.out.println(entryIterator.next());
}

/*OUTPUT
21=javaMadeSoEasy
11=audi
31=ferrari
*/


Iteration using enhanced for loop in java.
hashMap.entrySet() returns collection of values.
Set<Entry<Integer, String>> entrySet=hashMap.entrySet();
for(Entry<Integer, String> entry:entrySet){
   System.out.println(entry);
}


iterator returned is fail fast in java. Means any structural modification made to HashMap like adding or removing elements during Iteration will throw java.util.ConcurrentModificationException.
Few more important points about iterator >
  • Removing element by using iterator may throw IllegalStateException
  • If we add some key which is already present in set than no exception is thrown because size of map remains same (it is not structural modification ).


12) Some other important methods of java.util.HashMap in java


isEmpty() method returns true if this map contains any key-value pair.


clear() method removes all key-value pair from map.

13) synchronizing java.util.HashMap in java
We can synchronize hashMap by using Collections’s class synchronizedList method.
Map synchronizedMap = Collections.synchronizedMap(hashMap);
Now, no 2 threads can access same instance of map concurrently.


14) Complexity of methods in HashMap in java
Operation/ method
Worst case
Best case
put(K key, V value)
O(n)
O(1)
get(Object key)
O(n)
O(1)

15) Features of java.util.HashMap
  1. HashMap enables us to store data in key-value pair form in java.


  1. HashMap is implementation of the java.util.map interface in java.


  1. Duplicate key- HashMap does not allows to store duplicate keys. If the map already contains a mapping for the key, the old value is replaced in java.


  1. Null elements - One null key can be added in HashMap. And null values are also allowed in HashMap in java.
  2. Insertion order - HashMap does not maintains insertion order in java.
Example in java-
Let’s say we add 3 elements in hashMap
hashMap.put(1,"ind");    
hashMap.put(2,"aus");    
hashMap.put(3,"sa");

On displaying insertion order will not be maintained i.e.
3,sa
2,aus
1,ind

  1. synchronized - HashMap is not synchronized (because 2 threads on same HashMap object can access it at same time) in java.


  1. Performance - HashMap is not synchronized, hence its operations are faster as compared to some other synchronized implementation of map interface in java.

16) When to use java.util.HashMap in java


  1. HashMap can be used when we want to store data in key-value pair form in java.


  1. HashMap can be used when we want to store only one null key in java.


  1. HashMap can be used when value corresponding to key might be null in java.


  1. HashMap can be used when we don’t care about insertion order in java.


  1. HashMap can be used when we are not working in multithreading environment in java.

17) What is Load Factor in java?
Default load factor is 0.75
That means when set will be 75% filled,  it’s capacity will be doubled.


Example in java >
Initially when number of elements is 0,  default capacity =16, Load Factor =0.75, HashMap is 0% full.


number of elements
capacity of HashMap
Load factor
HashMap filled in %age
0
16
0.75
0%
4
16
0.75
25%
8
16
0.75
50%
11
16
0.75
68.7%
When next element will be added (i.e. 12th element), hashMap will be 75% filled and capacity will be doubled i.e. from 16 to 32.
12
32
0.75
37.5%

So in this Collection framework tutorial we learned what is java.util.HashMap in Collection framework in java.

Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.

RELATED LINKS>

ArrayList in java

HashSet in java





IdentityHashMap in java with program



WeakHashMap in java



EnumMap in java with program



Basic Collection - All properties in tabular form >

Collection - List, Set and Map all properties in tabular form


Collection hierarchy >

Map hierarchy in java - Detailed - HashMap, Hashtable, ConcurrentHashMap, LinkedHashMap, TreeMap, ConcurrentSkipListMap, IdentityHashMap, WeakHashMap, EnumMap classes


ConcurrentModificationException , Fail-fast and Fail-safe >

ConcurrentModificationException, Fail-fast and Fail-safe in detail in java


Important Similarity and Differences >
Map Differences >

HashMap and Hashtable - Similarity and Differences


HashMap and ConcurrentHashMap - Similarity and Differences


HashMap vs Hashtable vs LinkedHashMap vs TreeMap - Differences



HashMap vs IdentityHashMap - Similarity and Differences with program



Important Similarity and Differences Collection classes in concurrent and non-concurrent packages >


TreeSet vs ConcurrentSkipListSet - Similarity and Differences with program



TreeMap vs ConcurrentSkipListMap - Similarity and Differences with program





HashMap - Iterate on keys by obtaining keySet, Iterate on values by obtaining values, Iterate on entry by obtaining entrySet


HashMap - Iterator on keySet, values and entrySet is fail-safe or fail-fast?


HashMap - synchronizing map using Collections.synchronizedMap



ConcurrentSkipListMap - Iterator on keySet, values and entrySet is fail-safe or fail-fast?



Sorting Collection by implementing comparator and Comparable, using TreeMap and TreeSet, Collections.sort and Arrays.sort >

Sort Map by key in Ascending and descending order by implementing Comparator interface and overriding its compare method and using TreeMap



Sort Map by value in Ascending and descending order by implementing Comparator interface and overriding its compare method


eEdit
Must read for you :