Map interface with implementation classes

Map interface stores elements in the form of key-value pairs in java. If the key is provided then its corresponding value can be obtained. Of course, the keys should have unique values. Map interface implemented classes are,
  • HashMap
  • HashTable
  • LinkedHashMap
  • TreeMap
Methods of Map implemented classes:
  • value put(key, value) : This method stores key-value pairs.
  • value get(Object key) : This method returns corresponding value when key is given. If the key does not have a value associated with it, then it returns null.
  • Set<K> keySet() : This method, when applied on a map converts it into a Set where only keys will be stored.
  • Collection<V> values() : This method, when applied on a HashMap objects returns all the values of the HashMap into Collection objects.
  • value remove(Object key) : This method removes the key and corresponding value from the map.
  • void clear() : This method removes all the key-value pairs.
  • boolean isEmpty() : This method returns true if there are no key-value pairs in the map.
  • int size() : This method returns no.of key-value pairs contains the map
HashMap:
HashMap is a collection that stores elements in the form of  key-value pairs. If the key is provided, its corresponding value can be easily retrieved from the HashMap. Keys should be unique. This means we cannot use duplicate data for keys in the HashMap.

HashMap is not synchronized and hence while using multiple threads on HashMap object, we get unreliable results. We can write HashMap class as,
1
2
3
4
5
class HashMap<K,V>

public class HashMap<K,V>
    extends AbstractMap<K,V>
       implements NavigableMap<K,V>,cloneable,Serializable

Where K represents the type of key element and v represents the type of value element. To store a String as key and Integer as its value, we can create the HashMap as,
1
HashMap<String,Integer> hm = new HashMap<String,Integer>();

Capacity of the HashMap:
In the above we didn't mention any capacity of HashMap. The default initial capacity of this HashMap will taken as 16 and the load factor as 0.75. Load factor represents at what level the HashMap capacity should be doubled.

For example, the product of capacity and load factor = 16 * 0.75 = 12. This represents that after storing the 12th key-value pair into HashMap, its capacity will become 32.

We can also create HashMap the following ways:  Here, 70 represents the capacity of HashMap.
1
HashMap<String,Integer> hm = new HashMap<String,Integer>(70);

Here, 70 is the initial capacity and 0.6 is the load factor.
1
HashMap<String,Integer> hm = new HashMap<String,Integer>(70,0.6);

Methods of HashMap class:
In the above all Map methods are applicable for HashMap. Here is the example to show the use of HashMap.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.javatbrains.collections;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class HashMapDemo {

     public static void main(String[] args) {
          /* Creating HashMap object */
          HashMap<String, Integer> hm = new HashMap<String, Integer>();
          /* inserting key-value pairs using put() method */
          hm.put("Dhoni", 183);
          hm.put("Sachin", 200);
          hm.put("Kohli", 183);
          hm.put("Sourav", 183);
          hm.put("Rohit", 264);
          /* Printing the size of HashMap */
          System.out.println("Size of HashMap : "+ hm.size());
          /*
          * Checking HashMap is empty or not. If HashMap is not empty, will
          * display keys and values
          */
          if(!hm.isEmpty()) {
              /*Displaying all keys*/
              System.out.println("HashMap Keys: "+hm.keySet());
              /*Displaying all the values*/
              System.out.println("HashMap Values: "+hm.values());
              /*Storing all keys into a Set*/
              Set<String> set = hm.keySet();
              Iterator<String> it = set.iterator();
              System.out.println("Key-value pairs: ");
              while(it.hasNext()){
                   /*Getting individual key from Iterator*/
                   String key = it.next();
                   /*Getting respective value by passing Key*/
                   Integer value = hm.get(key);
                   /*Displaying key-value pairs*/
                   System.out.println("\t\t"+key +"-"+value);
              }
          }
     }
}
OutPut:
     Size of HashMap : 5
     HashMap Keys: [Rohit, Sourav, Sachin, Dhoni, Kohli]
     HashMap Values: [264, 183, 200, 183, 183]
     Key-value pairs:
              Rohit-264
              Sourav-183
              Sachin-200
              Dhoni-183
              Kohli-183

HashTable:
HashTable is similar to HashMap which can store elements in the form of key-value pairs. But, HashTable is synchronized assuring proper results even if multiple threads act on it simultaneously. We can write HashTable as,
1
2
3
4
5
 class HashTable<K,V>

 public class HashTable<K,V>
    extends Dictionary<K,V>
       implements Map<K,V>,cloneable,Serializable

Where K represents the type of key and V represents the type of value element. For example, to store String as key and String as value, we can create a HashTable as,
1
HashTable<String,String> ht = new HashTable<String,String>();

Here, we didn't mention any capacity of the HashTable. The default initial capacity if this HashTable will be taken as 11 and load factor as 0.75. Load factor represents at what level HashTable capacity should be doubled. For example, The product of capacity and load factor = 11 * 0.75 = 8.25. This represents that after storing 8th key-value pair into HashTable, its capacity will become 22.

we can also create HashTable in the following ways:
1
HashTable<String,String> ht= new HashTable<String,String>(70);

Here, 70 is the initial capacity of the HashTable,
1
HashTable<String,String> ht = new HashTable<String,String>(70,0.5);

Here, 70 is the initial capacity and 0.5 is the load factor of HashTable.

Methods of HashTable class:
All the above declared methods are same as HashTable method. Here is the example of HashTable which contains the mobile numbers as keys and name as values.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.javatbrains.collections;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

public class HashTableDemo {

     public static void main(String[] args) {
          /* Creating HashTable object with mobile
          * number as key and name as value
          */
          Hashtable<String, String> ht = new Hashtable<String, String>();
         
          /* inserting key-value pairs by using put method */
          ht.put("8888888888", "Just Dial");
         
          /* Inserting empty value means null */
          ht.put("", "");
          ht.put("9848022338", "Siva Mani");
         
          /*
          * Checking does HashTable is empty or not.
          * If HashTable not empty print the size
          */
          if(!ht.isEmpty()) {
              System.out.println("Size of HashTable:"+ ht.size());
              /*Displaying all keys*/
              System.out.println("HashMap Keys: "+ht.keySet());
              /*Displaying all the values*/
              System.out.println("HashMap Values:"+ ht.values());
              /*Storing all keys into a Set*/
              Set<String> set = ht.keySet();
              Iterator<String> it = set.iterator();
              System.out.println("Key-value pairs: ");
              while(it.hasNext()){
                   /*Getting individual key from Iterator*/
                    String key = it.next();
                   /*Getting respective value by passing Key*/
                   String value = ht.get(key);
                   /*Displaying key-value pairs*/
                   System.out.println("\t\t"+key +"-"+value);
              }
          }
     }
}
OutPut:
     Size of HashTable: 3
     HashMap Keys: [8888888888, 9848022338, ]
     HashMap Values: [Just Dial, Siva Mani, ]
     Key-value pairs:
              8888888888-Just Dial
              9848022338-Siva Mani

LinkedHashMap:
HashTable and LinkedList implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries.

LinkedHashMap class will declare as the below,
1
2
3
4
5
 class LinkedHashMap<K,V>

 public class LinkedHashMap<K,V>
     extends HashMap<K,V>
        implements Map<K,V>

Will create the object of LinkedHashMap as
1
LinkedHashMap<K,V> lm = new LinkedHashMap<K,V>();

LinkedHashMap is not synchronized, when two or more threads are acting simultaneously it will give unreliable results. The load factor and capacity is same as the HashTable.

TreeMap:
TreeMap is a Red-Black tree based NavigableMap implementation. It stores the elements in the form of key-value pairs. TreeMap is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time.

TreeMap class will declare as the below,
1
2
3
4
5
class TreeMap<K,V>

 public class TreeMap<K,V>
     extends AbstractMap<K,V>
       implements NavigableMap<K,V>,cloneable,Serializable

TreeMap is not synchronized and hence while using multiple threads on TreeMap object, we get unreliable results. We can write TreeMap class as,
1
TreeMap<String,Integer> tm = new  TreeMap<String,Integer>();

TreeMap default value is 16 and load factor 0.75, same as the HashMap. We can also define the TreeMap as like below,
Here, 60 is the capacity of the TreeMap,
1
TreeMap<String,Integer> tm = new  TreeMap<String,Integer>(60);

Here, 60 is the capacity and 0.6 is the load factor.
1
TreeMap<String,Integer> tm = new TreeMap<String,Integer>(60,0.6);

Method of TreeMap class:
Methods which are defined under Map Interface are also available in its subclasses. Additionally, TreeMap contains few of other methods.  Here is the example to show the use of the TreeMap,
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.javatbrains.collections;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapDemo {

     public static void main(String[] args) {
          TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
          tm.put("One", 1);
          tm.put("Two", 2);
          tm.put("Three", 3);
          tm.put("Four", 4);

          if(!tm.isEmpty()) {
              System.out.println("Size of the TreeMap: "+ tm.size());
              System.out.println("All Keys: "+ tm.keySet());
              System.out.println("All Values: "+ tm.values());

              Set<String> keys = tm.keySet();
              Iterator<String> it = keys.iterator();
              while(it.hasNext()) {
                   String key = it.next();
                   Integer value = tm.get(key);
                   System.out.println("\t\t"+ key +"-"+ value);
              }
          }
     }
}
OutPut:
     Size of the TreeMap: 4
     All Keys: [Four, One, Three, Two]
     All Values: [4, 1, 3, 2]
              Four-4
              One-1
              Three-3
              Two-2

If you have observed the difference of the output in the above class executions, TreeMapDemo has given the output in an ascending order. But, not in the previous two examples. So, TreeMap stores elements in the ascending order.

Difference between HashMap and HashTable?
           HashMap
          Hashtable
1. HashMap object not synchronized by default.
1. Hashtable object is synchronized by default.
2. In case of a single thread, using HashMap is faster than Hashtable.
2. In case of multiple threads, using HashTable is advisable. With a single thread, Hashtable becomes slow.
3. HashMap allows null keys and null values to be stored.
3. Hashtable does not allow null keys or values.
4. Iterator in the HashMap is fail-fast. This means Iterator will produce exception it concurrent updates are made to HashMap.
4. Enumeration for the Hashtable is not fail-fast. This means even if concurrent updates are done in Hashtable. There will not be any incorrect results produced by the Enumeration.

Comments

Popular posts from this blog

Hibernate auto increment with example

how to count the page views by using JSP

Multithreading in java with example

How to retrieve data from table by using JDBC with example

Prime, Fibonacci and Factorial number with example in java

How to insert images into database using JDBC?

How to sort list of objects in java with examples

String interview questions and answers

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Store file into table by using JDBC with example