Saturday, October 22, 2016

Java HashMap with example

This is one of the important topic in java,every java developer have knowledge on it.Since while you are developing software projects Hashmap class frequently used in projects.At the same time ArrayList class also used in real time software projects. By the end of this article you will learn complete knowledge on Hashmap with example. Many Developers get confused difference between HashSet and HashMap but after go through this article you must come out from it,I hope you would confident on HashMap topic after read this.

           The Java library provides two general purpose implementations for maps. They are HashMap and TreeMap. Both classes implements from Map interface.

HashMap: 

It is a collection that stores elements in the form of key-value pairs.Here keys should be unique.This means we can not use duplicate data for keys in the HashMap. The values associated with keys are not hashed or compared.However, HashMap is not synchronized and hence while using multiple threads on HashMap Object,we get unreliable result.

When to use HashMap In real time:


If you just need a Map, and you don not care about the order of the elements while iterating through it,you can use HashMap. Since HashMap is not sorted or ordered.The values can be null,but the key should be unique.So you can have one null value for key.But it allows only one null key.

We can write HashMap class as:

class HashMap<K,V>

where K represents the type of key element and V represents the type of value element.
For example,to store a String as key and an Integer object as its value,we can create the HashMap as:

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

Here is how you setup a HashMap for storing a employees:

Map<String,employee>staff=new HashMap<String,employee>();//HashMap implements Map.

Employee lucky=new Employee("lucky reddy");
staff.put("778977687",lucky);

In this case the Key is a String and corresponding value is the  Employee Object. To retrieve an object you must use a key. See the below how retrieve an object

String s="778977687";
e=staff.get(s);//gets lucky

Note: If no information is stored in the Map with the particular key specified,then get returns null.

Key must be unique. You can not store two values with the same key.If you the put method with the same key,then the second value replace the first one. 

The default initial capacity of this HashMap will be taken as 16 and the load factor as 0.75.Load Factor represents at what level the HashMap capacity should be doubled.

HashMap class methods:

HashMap class includes the fallowing methods:


  • value put(key,value);//this method stores key-value pair into the HashMap
  • value get(Object Key);//This method returns corresponding value 
  • Set<k> KeySet();//This method,when applied on a HashMap converts it into a Set where only keys will be stored.
  • value remove(Object key);//This method removes the key and corresponding value from the HashMap
  • Void clear();//this method removes all the key-value pairs from the Map
  • boolean isEmpty();//this method returns true if there are no key-value pairs in the HashMap
  • int size();//This method returns number of key-value pairs in the HashMap
Real Time Example:

Where we want to create a telephone Book using a HashMap. In this book,we store name of the person and his telephone number. Since the name is String and the telephone number is taken as Long type object.

Here String name is Key and telephone number which is Long type is its value.Using put() method,we can store the key-value pair.




import java.io.*;
import java.util.*;
class HashMapDemo
{
public static void main(String args[])throws IOException
{
//create HashMap

HashMap<String,Long> hm=new HashMap<String,Long>();

//variables
String name,str;
Long phno;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

//Menu

while(true)
{
System.out.println("1.Enter phone entries:");
System.out.println("2.Lookup in the book");
System.out.println("3.Display name in book:");
System.out.println("4.Exit:");

System.out.println("enter your choice");
int n=Integer.parseInt(br.readLine());

switch(n)
{
case 1: System.out.println("Enter name");
            name=br.readLine();
            System.out.println("enter phone:");
            phno=br.readLine();
            phno=new Long(str);
//Now store name and phno into HashMap
           hm.put(name,phno);
            break;
case 2:   System.out.println("enter name");
               name=br.readLine();
               name=name.trim()//remove unnecessary spaces
            //pass name and get phno
              phno=hm.get(name);
               System.out.println("phno: "+phno);
                break;

case 3: //use KeySet() to display the names
           //create HashSet object to store name and refer it by Set reference
             Set<String> s=new HashSet<String>();
               s=hm.KeySet();
              System.out.println(s);
                  break;
case 4:  return;
}
}
}
}

Output:

E:\javaprograms>javac HashMapDemo.java

E:\javaprograms>java HashMapDemo
1.Enter phone entries:
2.Lookup in the book
3.Display name in book:
4.Exit:
enter your choice
1
Enter name
lucky
enter phone:
8686868686
1.Enter phone entries:
2.Lookup in the book
3.Display name in book:
4.Exit:
enter your choice
2
enter name
lucky
phno: 8686868686
1.Enter phone entries:
2.Lookup in the book
3.Display name in book:
4.Exit:
enter your choice
3
[lucky]
1.Enter phone entries:
2.Lookup in the book
3.Display name in book:
4.Exit:
enter your choice




No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...