I want to now make use of this ArrayList with all the values and put it in a hashMap. How do i do it? Please help. In hashMap, values from Dept class will be in key and value will be auto incremented.
public class Main {
public static void main(String[] args) {
List<Dept> list = new ArrayList<Dept>();
Dept dept = new Dept("Mudit" , 4);
list.add(dept);
Dept dept1 = new Dept("Ashish" , 3);
list.add(dept1);
Dept dept2 = new Dept("Rahul" , 2);
list.add(dept2);
Dept dept3 = new Dept("Santos" , 3);
list.add(dept3);
Iterator<Dept> itr = list.iterator();
while(itr.hasNext()) {
System.out.println("values = " +itr.next());
}
}
}
class Dept {
private String name;
private int id;
public Dept(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Hashmap needs a unique key for each value . Here assuming id to be your key .
Hashmap<Integer,Dept> map=new HashMap(Integer,Dept);
for(Dept d:list)
{
map.put(d.getId(),d);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.