Java HashMap

A HashMap is used to store key value pair. HashMap implements the Map interface and extends AbstractMap class.

public class HashMap<K,V> extends AbstractMap<K,V> 
implements Map<K,V>, Cloneable, Serializable  

Here K is Key and V is value within HashMap.

Features of HashMap

  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It does not maintain order.
  • It is unsynchronized means cannot be used in multi-threading environment.
  • Default capacity is 16 and Default load factor(0.75). It can contain up to 16 element and resizing of HashMap will occur when 13th element will be inserted. This is because load factor is 75%(.75) and this threshold will be crossed when you add 13th element(12+1).

Constructors of HashMap

  1. HashMap()
    This is default constructor with capacity 16 and load factor (.75).

    
    HashMap<String,String> map = new HashMap<String,String>();
    
    
  2. HashMap(int capacity)
    By this constructor method you can specify the capacity of map.
  3. HashMap(int capacity, float fillRatio)
    By this constructor method you can specify the capacity and load factor of map.

Commonly used methods of Map interface

  • public Object put(object key,Object value): It is used to add key value pair in Map.
  • public void putAll(Map map):It is used to insert the specified map in this map.
  • public Object remove(object key):It is used to removed the entry for specified key.
  • public Object get(Object key):It is used to get the value for specified key.
  • public boolean containsKey(Object key):It is used to verify that the specified key exists or not in map.
  • public boolean containsValue(Object value):It is used to verify that the specified value exists in Map or not.
  • public Set entrySet():It returns the Set containing all the keys and values.
  • public Set keySet():It returns all keys entries as Set from Map.

Example of HashMap to add elements

HashMapTest.java


package com.startwithjava.collections;

import java.util.HashMap;
import java.util.Map;

public class HashMapTest {
public static void main(String args[]){
 HashMap<Integer,String> map = new HashMap<Integer,String>;();
 map.put(1, "Raj Kumar");
 map.put(2, "Ram Kumar");
 map.put(3, "Sohan Kumar");
}
}

Example of HashMap to iterate elements using for-each loop

The entrySet() method returns set of Map.Entry<K,V>. Map.Entry is sub interface of Map interface.

 
public class HashMapTest { 
public static void main(String args[]){ 
HashMap<Integer,String> map = new HashMap<Integer,String>;(); 
map.put(1, "Raj Kumar");
 map.put(2, "Ram Kumar");
 map.put(3, "Sohan Kumar");
 //Map.Entry is used to get entry from Map 
 for(Map.Entry<Integer, String> entry:map.entrySet()){ 
  System.out.println("Key Value="+entry.getKey()+"\t Element Value="+entry.getValue()); 
 } 
 }
} 

Example of HashMap to iterate elements using Iterator

The entrySet() method returns set of Map.Entry  in the form of Set<Map.Entry<K, V>>. Map.Entry is sub interface of Map interface.

 
public class HashMapTest { 
public static void main(String args[]){ 
HashMap<Integer,String> map = new HashMap<Integer,String>;(); 
map.put(1, "Raj Kumar");
 map.put(2, "Ram Kumar");
 map.put(3, "Sohan Kumar");
 //Map.Entry is used to get entry from Map 
 Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
 Iterator<Map.Entry<Integer, String>> itr   = entrySet.iterator();
  while(itr.hasNext()){
      Map.Entry<Integer,String> entry = itr.next();
     System.out.println("Key Value="+entry.getKey()+"\t Element Value="+entry.getValue());
  }
 }
} 

Example of HashMap to get value by key


package com.startwithjava.collections;

import java.util.HashMap;
import java.util.Map;

public class HashMapTest {
public static void main(String args[]){
HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "Raj Kumar");
map.put(2, "Ram Kumar");
map.put(3, "Sohan Kumar");
String name = map.get(1);
System.out.println("Name:"+name);
}

}

Example of HashMap custom object for Key and Value

If you want to store your own class object as key then you need to override hashcode() and equals() methods in your own class. As HashMap works on the mechanism of hashing to assign an integer value to an object to speed up searching element by key. The overridden hashCode() method should return unique integer for each object. If more than one object has same hash value then equals() method has been checked for equality of both the objects.


package com.startwithjava;

public class Customer {
private int id;
private String name;
private String address;
public Customer(int id, String name, String address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
public Customer() {
super();
}
public int hashCode(){
return id;
}
public boolean equals(Object obj){
Customer cust = (Customer)obj;
return (id==cust.id) && (cust.name.equalsIgnoreCase(name));
}
public String toString(){
return("ID="+id+"\tName="+name+"\tAddress="+address);
}

}


package com.startwithjava;

import java.util.Date;

public class Order {
private double orderTotal;
private Date orderDate;

public Order(int id, double orderTotal, Date orderDate) {
super();
this.orderTotal = orderTotal;
this.orderDate = orderDate;
}

@Override
public String toString() {
return "Order [orderTotal=" + orderTotal
+ ", orderDate=" + orderDate + "]";
}
}


package com.startwithjava;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class HashMapCustomKey {

public static void main(String[] args) {

HashMap<Customer,Order> customerOrders = new HashMap<Customer,Order>();

Customer c1 = new Customer(1,"Ajay","New Delhi");
Customer c2 = new Customer(2,"Anil","Patna");

Order o1 = new Order(1,4500.75,new Date());
Order o2 = new Order(2,2580.75,new Date());

customerOrders.put(c1,o1);
customerOrders.put(c2,o2);


for(Map.Entry<Customer,Order> entry: customerOrders.entrySet()){
System.out.println("\nCustomer Info");
System.out.println(entry.getKey().toString());
System.out.println("Order Info");
System.out.println(entry.getValue().toString());
}
}

}

Leave a Reply