Friday, June 17, 2016

HashMap Class Java example

Hash Map Class

 HashMap is a collection that stores elements in the form of key-value pairs.If key is provided,its corresponding value can be retrieve easily.Keys should be unique .This means we cannot use duplicate data for keys in the HashMap.
HashMap is not synchronized and hence in case of multi threading we can get unreliable result.

Default Initial Capacity=16
Load Factor=0.75

HashMap Class Methods

  • value put(key,value)
  • value get(Object key)
  • Set<K> keySet()
  • Collection<V> values
  • value remove(Object key)
  • void clear()
  • boolean isEmpty()
  • int size()
Program Sample:


/**
 * 
 */
package com.collectionpack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class HashMapDemo {

/**
* @param args
* @throws IOException 
* @throws NumberFormatException 
*/
public static void main(String[] args) throws NumberFormatException, IOException
{
HashMap<String , Long> hm=new HashMap<>();
        String name,str;
        Long phone;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        while(true)
        {
        System.out.println("1. enter phone entries");
        System.out.println("2. lookup in the phone book");
        System.out.println("3. display name in book");
        System.out.println("4. exit");
       
        System.out.println("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 number: ");
str=br.readLine();
phone=new Long(str);
hm.put(name, phone);
break;
case 2:
System.out.println("Enter name: ");
name=br.readLine();
name=name.trim();
phone=hm.get(name);
System.out.println("Phone :"+phone);
break;
case 3:
Set<String> set=new HashSet<>();
set=hm.keySet();
System.out.println(set);
break;

default:
return;
}
        }
}

}

Output:

1. enter phone entries
2. lookup in the phone book
3. display name in book
4. exit
your choice: 
1
Enter name: 
abhinaw
Enter phone number: 
8130752107
1. enter phone entries
2. lookup in the phone book
3. display name in book
4. exit
your choice: 
2
Enter name: 
abhinaw
Phone :8130752107
1. enter phone entries
2. lookup in the phone book
3. display name in book
4. exit
your choice: 



No comments: