![](/img/trans.png)
[英]How do i create an arraylist of values from a nested HashMap in java?
[英]I have an arraylist of Dept type, Now i want this data to be used in HashMap containing all the values of arraylist in it. how do i do it?
我现在想利用这个 ArrayList 的所有值并将它放在一个 hashMap 中。 我该怎么做? 请帮忙。 在 hashMap 中,来自 Dept 类的值将在键中并且值将自动递增。
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 每个值都需要一个唯一的键。 这里假设id是你的key 。
Hashmap<Integer,Dept> map=new HashMap(Integer,Dept);
for(Dept d:list)
{
map.put(d.getId(),d);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.