Hash Map Example using iteration



To use Hash Map using Java

// Comment
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
packagecom.allinalljava;

importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.Map;
importjava.util.Set;

/**
 *
 * @author allinalljava.blogspot.com
 */
public class HashMapSample {
public static void main (String [] args)
{
Map m = new HashMap ();
Employee e = new Employee ("ram", 50000.0);
m.put ("123", e);
e = new Employee ("ganes", 30000.0);
m.put ("456", e);
e = new Employee ("rajesh", 49750.0);
m.put ("758", e);
Set entries = m.entrySet ();
Iterator iter = entries.iterator ();
while (iter.hasNext ())
{
Map.Entry me = (Map.Entry) iter.next ();
System.out.print (me.getKey () + " ");
e = (Employee) me.getValue ();
System.out.println (e.getName () + " " + e.getSalary ());
}
System.out.println ("Map size = " + m.size ());
System.out.println ("Empty: " + m.isEmpty ());
m.clear ();
System.out.println ("Map size = "+ m.size ());
System.out.println ("Empty: " + m.isEmpty ());
}
}


Employee.java

// Comment

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.allinalljava;

/**
 *
 * @author allinalljava.blogspot.com
 */
import java.util.*;
class Employee
{
private String name;
private double salary;
Employee (String name, double salary)
{
this.name = name;
this.salary = salary;
}
String getName ()
{
return name;
}
double getSalary ()
{
return salary;
}
}

Output

123 ram 50000.0
456 ganes 30000.0
758 rajesh 49750.0
Map size = 3
Empty: false
Map size = 0
Empty: true
raja P Web Developer

2 comments:

  1. How can I achieve this with Java 6 generics?

    ReplyDelete

  2. Refer the following program in order to achieve this in Java 6 generics

    http://allinalljava.blogspot.in/2012/10/hash-map-example-using-generic.html

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...