Hashmap in Java

Introduction to Hashmap in Java

A HashMap in Java is a data structure that stores key-value pairs. It is a part of the Java Collections Framework and is implemented using a hash table. HashMaps are known for their fast retrieval and insertion times, which makes them a popular choice for many different types of applications.

How to create a HashMap in Java

To create a HashMap in Java, you must first import the `java.util.HashMap` package. Once you have done that, you can create a HashMap using the following syntax:


HashMap<K, V> hashMap = new HashMap<>();
Where K is the type of the keys and V is the type of the values. For example, to create a HashMap that stores strings as keys and integers as values, you would use the following code:


  HashMap<String, Integer> hashMap = new HashMap<>();

How to add and retrieve data from a HashMap

To add a key-value pair to a HashMap, you can use the put() method. The following code shows how to add a key-value pair to the HashMap that we created in the previous example:


hashMap.put("name", 10);

To retrieve the value associated with a particular key, you can use the get() method. The following code shows how to retrieve the value associated with the name key from the HashMap:


Integer value = hashMap.get("name");
If the key does not exist in the HashMap, the get() method will return null.

Benefits of using HashMaps in Java

There are many benefits to using HashMaps in Java, including:

  • Fast retrieval and insertion times: HashMaps provide constant time access to elements, which means that retrieval and insertion of elements are very fast, usually O(1) time complexity.
  • Dynamic sizing: HashMaps are dynamically sized, which means that they can grow and shrink as needed. This makes them very efficient for storing data of varying sizes.
  • Null keys and values: HashMaps allow null keys and values. This can be useful in some cases, such as when you need to store data that may be missing or incomplete.

When to use HashMaps in Java

HashMaps should be used whenever you need to store data in a key-value format and you need fast retrieval and insertion times. Some examples of common use cases for HashMaps include:

  • Caching data
  • Storing user sessions
  • Implementing lookups
  • Building graphs and networks

Conclusion

HashMaps are a versatile and powerful data structure that can be used in a variety of applications. They are a popular choice for many different types of Java applications, including web applications, database applications, and distributed systems.

Exercises

Code for declaring an hashmap containing Registration Numbers and Names of Students


package practiceproject;
import java.io.*;
import java.util.*;
public class democlass {
  
    public static void main(String[] args) throws IOException { 
    HashMap<String, String> students = new HashMap<String, String>();
    students.put("12BCE001", "Satish");
    students.put("12BCE002", "Ram");
    students.put("12BCE003", "Sam");
    for(Map.Entry k:students.entrySet())
    {
      System.out.println(k.getKey()+" "+k.getValue());
    }
    }
} 

Code for Traversing an HashMap using keyset


import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Satish20BCE001{

public static void main(String[] args) throws IOException{
      
  HashMap<String, String> student = new HashMap<>();
  student.put("12bce001", "satish");
  student.put("12bce002", "ram");
  student.put("12bce003", "tom");
  student.put("12bce004", "jeff");
  for(String s:student.keySet())
  {
    System.out.println(student.get(s));
  }
}
}  

Demo code for removing an element from HashMap


package practiceproject;
import java.io.*;
import java.util.*;
public class democlass {

  public static void main(String[] args) throws IOException {
    
  HashMap<String, String> students = new HashMap<String, String>();
  students.put("12BCE001", "Satish");
  students.put("12BCE002", "Ram");
  students.put("12BCE003", "Sam");
  students.remove("12BCE001");
  for(Map.Entry m :students.entrySet())
  {
    System.out.println(m.getKey()+""+m.getValue());
  }
  
  }
} 

Demo Code for use of size and clear methods in HashMap


package practiceproject;
import java.io.*;
import java.util.*;
public class democlass {

  public static void main(String[] args) throws IOException {
    //clear method and size 
  HashMap<String, String> students = new HashMap<String, String>();
  students.put("12BCE001", "Satish");
  students.put("12BCE002", "Ram");
  students.put("12BCE003", "Sam");
  students.clear();
  System.out.println(students.size());
  /*for(Map.Entry m :students.entrySet())
  {
    System.out.println(m.getKey()+""+m.getValue());
  }*/
  
  }
} 

Code for demonstrating the use of get Method in HashMap


import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Satish20BCE001{
  
  public static void main(String[] args) throws IOException{
    HashMap<String, Integer> marks = new HashMap<>();
    marks.put("satish", 21);
    marks.put("ram", 33);
    marks.put("tom", 41);
    System.out.println(marks.get("ram"));
    
  }
} 

Code for searching an Hashmap for a key


import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Satish20BCE001{
  
  public static void main(String[] args) throws IOException{
    HashMap<String, Integer> marks = new HashMap<>();
    marks.put("satish", 21);
    marks.put("ram", 33);
    marks.put("tom", 41);
    if(marks.containsKey("ram"))
    {
      System.out.println("Element is found");
    }
    else
    {
      System.out.println("Element not found");
    }
    
  }
}  

Demo code for searching an HashMap for a value


import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Satish20BCE001{

public static void main(String[] args) throws IOException{
  HashMap<String, Integer> marks = new HashMap<>();
  marks.put("satish", 21);
  marks.put("ram", 21);
  marks.put("tom", 41);
  if(marks.containsValue(21))
  {
    System.out.println("Element found");
  }
  else
  {
    System.out.println("Element not found");
  }
  
}
}  

Demo code for replacing a value using a key in HashMap


  import java.io.*;
  import java.util.HashMap;
  import java.util.Map;
  import java.util.Scanner;
  import java.util.Set;
  public class Satish20BCE001{
  
  public static void main(String[] args) throws IOException{
    HashMap<String, Integer> marks = new HashMap<>();
    marks.put("satish", 21);
    marks.put("ram", 21);
    marks.put("tom", 41);
    marks.replace("tom", 41,44);
    for(Map.Entry<String, Integer> k:marks.entrySet())
    {
      System.out.println(k.getKey());
      System.out.println(k.getValue());
    }
  }
  }  

Create a hashmap containing country names and capitals of five countries. Provide the capital name for any country name given by the user


import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Satish20BCE001{
  
  public static void main(String[] args) throws IOException{
    boolean found=false;
    HashMap<String, String> country_capital = new HashMap<String,String>();
    country_capital.put("India","Delhi");
    country_capital.put("US","Washington");
    country_capital.put("UK","London");
    country_capital.put("Australia","Canberra");
    country_capital.put("Srilanka","Colombo");
    System.out.println("Enter the Country Name");
    Scanner input = new Scanner(System.in);
    String inputCountry = input.nextLine();
    for(Map.Entry<String, String> k :country_capital.entrySet())
    {
      if(inputCountry.equals(k.getKey()))
      {
        System.out.println("The Capital Name is "+k.getValue());
        found=true;
        break;
      }
    }
    if(!found)
    {
      System.out.println("No Such country in the list");
    }
  }
}