迭代hashmap

nit*_*hin 1 java collections hashmap

可能重复:
如何迭代Map中的每个条目?
如何迭代<String,POJO>的地图?

我编写了下面这段代码,但我仍然坚持迭代hashmap.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

class demo
{
    public static void main(String v[]) {
        ArrayList<String> contactIds = new ArrayList<String>();
        contactIds.add("2");
        contactIds.add("3");

        HashMap names = new HashMap();
        names =  getNames(contactIds);

        // I want to get the total size of the hashmap  - names
        // for ex now there are 6 elements inside hashmap.
        // How can I get that count?

    }


    private static HashMap getNames(ArrayList contactIds) {
        HashMap names = new HashMap();
        String params = null;
        List<String> list = new ArrayList<String>();
        for(int i=0; i<contactIds.size();i++) {
            params = contactIds.get(i).toString();

            list.add(0,"aer-1");
            list.add(1,"aer-2");
            list.add(2,"aer-3");

            names.put(params,list) ;
         }

        return names;
    }
}
Run Code Online (Sandbox Code Playgroud)

在这段代码中,地图中有六个元素,现在在main方法中,我如何迭代地图并获得总计数?

谢谢.

pau*_*sm4 6

你的问题被问到 - 并在这里回答:

如何有效地迭代地图中的每个条目?

for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)