簡體   English   中英

我有一個 Dept 類型的 arraylist,現在我希望在 HashMap 中使用這個數據,其中包含 arraylist 的所有值。 我該怎么做?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM