Updated March 28, 2023
Definition of Hashmap and Hashtable
Hashmap and Hashtable are some of the main data structures of java used according to the requirement. Both the data structure are part of the collection in Java. They have certain distinctions among themselves with some differences as well. This difference mainly revolves around the synchronization aspects like Hash map is non-synchronized whereas hashtable is synchronized. HashMap allows one null key, but there can be many numbers of keys as well. On the other hand, the Hash table does not follow any kind of ordering for numbers, and also it does not map to any other particular order.
Syntax 0f Hashmap and Hashtable
There is no particular syntax for Hashmap or Hashtable, but it is called within the method once we declare the collection while importing from the standard library with hashmap and hashtable also supported by a certain standard of the library.
Syntax for HashMap()
HashMap hm1 = new HashMap();
.
.
Set k_ys = hm1.keySet ();
for (obj k1: k_ys) {
hm1.put (objct & key_value pair);
}
Syntax for Hashtable()
Hashtable hs_tb = new Hashtable();
.
.
Enumeration ky_s = hs_tb.ky_s();
for (Enumeration en_0 = hs_tb.el() ; en.hasMoreel() ; en.nextel())
{
hs_tb.put (key & vl_pair);
}
In both cases, a ConcurrentModificationException will be present in the object definition with key-value and pair.
How do Hashmap and Hashtable work?
- Both Hashmap and Hashtable play a pivotal role, whether with collections frameworks or generally with respect to any of the scenarios being mentioned as part of the requirement.
- Hashmap doesnot preserve any specific order when used with Java as a programming language, so if a scenario comes where a specific order needs to be maintained, then the use of sorting gets arises for implementation.
- Both hashmap and hashtable implement the same interface with java.util.Map interface where they have very minor differences in terms of their working.
- Hashmap is non-synchronized, and it’s mostly used in a multithreaded environment where there it gets a way to access and process the Hashmap simultaneously.
- On the other hand, when compared to Hashmap, it behaves completely opposite in a sense it is synchronized in nature where it makes sure that one thread can access any of the multiple threads at a given point of time where the thread works by acquiring a lock to make other threads wait till it gets fully terminated.
- Since Hashmap doesnot consist of order and synchronization thus it makes use of some sorting techniques where the hashing with sorting takes place; then, it is needed to keep keys and values paired within it, which is mandatory.
- Using sorting within hashmap with TreeMap makes its perfect usage with the keys it provides. Also, LinkedHashMap which gets its uses.
- There is a convention that if in case we make use of LinkedHashMap, then it is needed to get the set converted into a list, and further that converted list gets added into LinkedHashMap in that very same order.
- Both have differences, although supports for the almost same set of libraries.
Examples of Hashmap and Hashtable
Different examples are mentioned below:
Example #1
This program demonstrates the Hashmap with an ability to store the key and value pair by creating a hashmap and parallelly inserting the values into it, as shown in the output below.
Code:
import java.util.*;
public class HashMapEx{
public static void main(String args[]){
HashMap<Integer,String> mp_0=new HashMap<Integer,String>();
mp_0.put(1,"Sedan");
mp_0.put(2,"SUV");
mp_0.put(3,"Micro");
mp_0.put(4,"Macro");
System.out.println("Iteration_with_map_for_working.");
for(Map.Entry mp_2 : mp_0.entrySet()){
System.out.println(mp_2.getKey()+" "+mp_2.getValue());
}
}
}
Output
Example #2
This program demonstrates the hashtable example where the hashtable takes into account the values in the form of marks for their respective subjects, as shown in the output below.
import java.util.*;
public class Hashtbl_ex
{
public static void main(String args[]){
Hashtable<Integer,String> hi_o=new Hashtable<Integer,String>();
hi_o.put(56,"Physics_marks");
hi_o.put(12,"Chem_mrks");
hi_o.put(100,"Bio_mrks");
hi_o.put(13,"Maths_mrks");
for(Map.Entry m_0:hi_o.entrySet()){
System.out.println(m_0.getKey()+" "+m_0.getValue());
}
}
}
Output:
Example #3
This program demonstrates the Hashmap where the List of students defined and traversed is getting updated using the update and replace function incorporating respective keys and elements as shown in the output below.
import java.util.*;
public class HashMap3_Ex{
public static void main(String args[]){
HashMap<Integer,String> hm_0=new HashMap<Integer,String>();
hm_0.put(10,"Anu_0");
hm_0.put(11,"Jack_1");
hm_0.put(12,"Rosy_8");
System.out.println("A_List_of_Students:");
for(Map.Entry m_2:hm_0.entrySet())
{
System.out.println(m_2.getKey()+" "+m_2.getValue());
}
System.out.println("List_of_elements_updated_for:");
hm_0.replace(10, "Anu_1");
for(Map.Entry m_2:hm_0.entrySet())
{
System.out.println(m_2.getKey()+" "+m_2.getValue());
}
System.out.println("list_of_elements_updated..:");
hm_0.replace(12, "Rosy_0", "Raj_7");
for(Map.Entry m_2:hm_0.entrySet())
{
System.out.println(m_2.getKey()+" "+m_2.getValue());
}
System.out.println("Next_List_of-elemets_updated:");
hm_0.replaceAll((k,v) -> "Joy_8");
for(Map.Entry m_2:hm_0.entrySet())
{
System.out.println(m_2.getKey()+" "+m_2.getValue());
}
}
}
Output:
Example #4
This program demonstrates the hashtable where the elements inserted within the stack can be removed with the same index, which in turn can return the same set of elements to the end-user, as shown in the output below.
import java.util.*;
public class Hashtabl3_Ex
{
public static void main(String args[])
{
Hashtable<Integer,String> mp_0=new Hashtable<Integer,String>();
mp_0.put(10,"Ani_0");
mp_0.put(12,"Revi_1");
mp_0.put(11,"Biden_8");
mp_0.put(13,"Rahl_0");
System.out.println("Representation_Before_map "+ mp_0);
mp_0.remove(12);
System.out.println("Representation_After_map_removal: "+ mp_0);
}
}
Output:
Example #5
This program demonstrates sorting being performed on the values of HashMap, as shown in the output below.
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class SortHashMapValue
{
public static void main(String[] args)
{
HashMap<Integer, String> hm_0 = new HashMap<Integer, String>();
hm_0.put(7, "Anu_0");
hm_0.put(8, "Ash_1");
hm_0.put(10, "Zoy_8");
hm_0.put(18, "Ysh_7");
hm_0.put(11, "Prvn_0");
hm_0.put(37, "Bby_6");
hm_0.put(1, "Rtesh_0");
System.out.println("Representation_Before_Sorting");
Set set = hm_0.entrySet();
Iterator itr_7 = set.iterator();
while(itr_7.hasNext())
{
Map.Entry mp_1 = (Map.Entry)itr_7.next();
System.out.println("Roll no: "+mp_1.getKey()+" Name: "+mp_1.getValue());
}
Map<Integer, String> mp_2 = sortValues(hm_0);
System.out.println("\n");
System.out.println("Representation_After_Sorting:");
Set st2 = mp_2.entrySet();
Iterator itr2 = st2.iterator();
while(itr2.hasNext())
{
Map.Entry je2 = (Map.Entry)itr2.next();
System.out.println("Roll no: "+je2.getKey()+" Name: "+je2.getValue());
}
}
private static HashMap sortValues(HashMap mp_2)
{
List lst_0 = new LinkedList(mp_2.entrySet());
Collections.sort(lst_0, new Comparator()
{
public int compare(Object l1, Object l2)
{
return ((Comparable) ((Map.Entry) (l1)).getValue()).compareTo(((Map.Entry) (l2)).getValue());
}
});
HashMap sorthsh_Map = new LinkedHashMap();
for (Iterator it_9 = lst_0.iterator(); it_9.hasNext();)
{
Map.Entry etry = (Map.Entry) it_9.next();
sorthsh_Map.put(etry.getKey(), etry.getValue());
}
return sorthsh_Map;
}
}
Output:
Conclusion
HashMap and Hashtable both use almost the same set of the library but have helped boost the key and value pair lists when it comes to maintaining them. The data structure has also helped the collection framework by providing developers leverage to play around with a huge set of elements defined in terms of keys and values.
Recommended Articles
This is a guide to Hashmap and Hashtable. Here we also discuss the definition and how hashmap and hashtable work? Along with different examples and their code implementation. You may also have a look at the following articles to learn more –