Thursday, March 5, 2009

Different ways to get HashMap elements



package myutil;

import java.util.*;
public class HashMapEx1 {


public static void main(String... args) {
HashMap map=new HashMap();
map.put("orange",new Integer(1000));
map.put("apple",new Integer(2000));
map.put("banana",new Integer(3000));
map.put("grapes",new Integer(4000));
System.out.println("The Map "+map);
System.out.println(map.put(("orange"),new Integer(1001)));
System.out.println("map "+map);
//using key set
Set s=map.keySet();
System.out.println("The Key Set"+s);
// using values
Collection values=map.values();
System.out.println("The Values Are "+values);
// entry set
Set s1=map.entrySet();
System.out.println("The Entry Set"+s1);
//iterator
Iterator it=s1.iterator();
while(it.hasNext())
{
Map.Entry m1=(Map.Entry)it.next();
System.out.println(m1.getKey()+"........"+m1.getValue());
if(m1.getKey().equals("apple")){
m1.setValue(new Integer(6000));
System.out.println(m1.getValue());
}
}

}
}

output:
The Map {orange=1000, grapes=4000, apple=2000, banana=3000}
1000
map {orange=1001, grapes=4000, apple=2000, banana=3000}
The Key Set[orange, grapes, apple, banana]
The Values Are [1001, 4000, 2000, 3000]
The Entry Set[orange=1001, grapes=4000, apple=2000, banana=3000]
orange........1001
grapes........4000
apple........2000
6000
banana........3000



0 comments:

Post a Comment