How to storing Java Object In HashMap

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapStoreObject {

public static void main(String[] args) {

Map<Integer,Emp> hm = new HashMap<Integer, Emp>();

hm.put(1, new Emp(100, “dk”) );
hm.put(2, new Emp(102, “kapil”) );
hm.put(3, new Emp(105, “anup”) );
hm.put(4, new Emp(205, “kapil”) );
hm.put(5, new Emp(110, “pk”) );

Set<Integer> keys = hm.keySet();

for (Integer key : keys) {

Emp emp = hm.get(key);
System.out.println(” Id = “+emp.getId()+” name = “+emp.getName());
}

}

}

class Emp{

private int id;
private String name;

public Emp(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

Output:

Id = 100 name = dk

Id = 102 name = kapil

Id = 105 name = anup

Id = 205 name = kapil

Id = 110 name = pk

 

Leave a Reply

Your email address will not be published. Required fields are marked *

96 − 91 =