Friday, November 2, 2012

Hash Map and Hast Table in Java

Here is an example of usage of Hash Table and Hash Map in Java

Hash Map
package com.giri.test;

import java.util.*;

public class HashTable {
 
 public static void main(String[] args) {
  Hashtable hashTable = new Hashtable();
  Enumeration names;
  String str;
  double money;
  
  // this hash table - shows who has how much money in their pocket
  hashTable.put("Mohit Khatri", new Double("100.55"));
  hashTable.put("Naveen Raju", new Double("210.75"));
  hashTable.put("Saikat Mukherjee", new Double("1000.99"));
  hashTable.put("Deepika", new Double("2000.4"));
  
  // this returns an enumeration
  names = hashTable.keys();
    
  while(names.hasMoreElements()) {
   str = (String) names.nextElement();
   System.out.println("String: " + str + " , Money: "+ hashTable.get(str));
  }
  
  System.out.println("\n");
  
  // add 5000 to Deepika's available funds
  money = ((Double) hashTable.get("Deepika")).doubleValue();
  hashTable.put("Deepika", new Double(money+5000.0));
  
  System.out.println("\n Deepika's new left over money: "+ hashTable.get("Deepika"));

 }

}

Output:

String: Deepika , Money: 2000.4
String: Mohit Khatri , Money: 100.55
String: Naveen Raju , Money: 210.75
String: Saikat Mukherjee , Money: 1000.99

 Deepika's new left over money: 7000.4
Hash Table with Set
package com.giri.test;

import java.util.*;

public class HashTableSet {
 
 public static void main(String[] args) {
  Hashtable hashTable = new Hashtable();
  Enumeration names;
  String str;
  double money;
  
  // this hash table - shows who has how much money in their pocket
  hashTable.put("Mohit Khatri", new Double("100.55"));
  hashTable.put("Naveen Raju", new Double("210.75"));
  hashTable.put("Saikat Mukherjee", new Double("1000.99"));
  hashTable.put("Deepika", new Double("2000.4"));
  

  Set set = hashTable.keySet();
  
  // get iterator
  Iterator it = set.iterator();
  
  while(it.hasNext()) {
   str = (String) it.next();
   money = (Double) hashTable.get(str);
   System.out.println("\n String: "+str + " , " + money);
  }
  
  System.out.println();
  
  // add 1500.55 to Deepika's funds
  
  money = ((Double) hashTable.get("Deepika")).doubleValue();
  hashTable.put("Deepika", new Double(1500.55+money));
  
  System.out.println(" Deepika's new funds: " + (Double) hashTable.get("Deepika"));

 }

}

Output:

 String: Deepika , 2000.4

 String: Mohit Khatri , 100.55

 String: Naveen Raju , 210.75

 String: Saikat Mukherjee , 1000.99

 Deepika's new funds: 3500.95

No comments :

Post a Comment