HashMap in java with examples

HashMap is most common Collection which we use now a days. It stores entry in key value pair.
  1. HashMap implements Map interface which maps key to value.
  2. It is not synchronized and is not thread safe.
  3. Duplicate keys are not allowed
  4. One null key and multiple null values are allowed

Java HashMap tutorial:

    HashMap in java How HashMap works in java hash and indexfor method in HashMap hashcode and equals method in java How to sort HashMap by keys and values Difference between HashMap and HashSet Difference between HashMap and Hashtable How to iterate over HashMap
HashMap<Integer,String> employeeHashmap=new HashMap<Integer,String>();
employeeHashmap.put(1,"Arpit");
employeeHashmap.put(2,"John"); 

Example:

package org.arpit.java2blog;

import java.util.HashMap;

public class HashMapBuiltMain {

 public static void main(String[] args) {
  HashMap<Integer, String> employeeHashmap = new HashMap<Integer, String>();
  employeeHashmap.put(1, "Arpit");
  employeeHashmap.put(2, "John");
  employeeHashmap.put(3, "Martin");
  employeeHashmap.put(4, "Vaibhav");

  // Iterating HashMap Using keySet() and for each loop
  System.out.println("Iterating HashMap Using keySet() and for each loop");
  System.out.println("-----------------------------");
  for (Integer empId : employeeHashmap.keySet()) {
   System.out.println("EmpId:" + empId + " and  Emp Name:" + employeeHashmap.get(empId));

  }
  System.out.println("-----------------------------");
 }
}

When you run above program, you will get below output
Iterating HashMap Using keySet() and for each loop
-----------------------------
EmpId:1 and  Emp Name:Arpit
EmpId:2 and  Emp Name:John
EmpId:3 and  Emp Name:Martin
EmpId:4 and  Emp Name:Vaibhav
-----------------------------

Storing Custom objects as Key:

You can store custom objects as Key in HashMap but you should implement hashcode and equals method, otherwise it may not work as expected.  You may go through hashcode and equal method to understand it better.

Create a class called Country.java
package org.arpit.java2blog;  
public class Country  {  
  
 String name;  
 long population;  
   
 public Country(String name, long population) {  
  super();  
  this.name = name;  
  this.population = population;  
 }  
 public String getName() {  
  return name;  
 }  
 public void setName(String name) {  
  this.name = name;  
 }  
 public long getPopulation() {  
  return population;  
 }  
 public void setPopulation(long population) {  
  this.population = population;  
 }
 
@Override
public int hashCode() {
 final int prime = 31;
 int result = 1;
 result = prime * result + ((name == null) ? 0 : name.hashCode());
 result = prime * result + (int) (population ^ (population >>> 32));
 return result;
}
@Override
public boolean equals(Object obj) {
 if (this == obj)
  return true;
 if (obj == null)
  return false;
 if (getClass() != obj.getClass())
  return false;
 Country other = (Country) obj;
 if (name == null) {
  if (other.name != null)
   return false;
 } else if (!name.equals(other.name))
  return false;
 return true;
}
  
}  

Create another class HashMapMain.java
package org.arpit.java2blog;

import java.util.HashMap;

public class HashMapMain {

 public static void main(String args[])
 {
 // HashMap with Country name as key and capital as value
 // HashMap stores elements in key value pairs
  HashMap<String,String> countryCapitalMap=new HashMap<String,String>();
  countryCapitalMap.put("India","Delhi");
  countryCapitalMap.put("Japan","Tokyo");
  countryCapitalMap.put("France","Paris");
  countryCapitalMap.put("Russia","Moscow");

  System.out.println("-----------------------------");
  // Iterating HashMap Using keySet() and for each loop
  System.out.println("Iterating HashMap Using keySet() and for each loop");
  for (String countryKey:countryCapitalMap.keySet()) {
   System.out.println("Country:"+ countryKey +" and  Capital:"+countryCapitalMap.get(countryKey));

  }
  System.out.println("-----------------------------");
}

}

When you run above program, you will get below output
-----------------------------
Iterating HashMap Using keySet() and for each loop
Country:France and  Capital:Paris
Country:Russia and  Capital:Moscow
Country:Japan and  Capital:Tokyo
Country:India and  Capital:Delhi
-----------------------------


HashMap is not synchronized by default but we can make it synchronized using
Collections.synchronizedMap(new HashMap<String, String>());






Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012