获取HashMap的所有子项<integer,arraylist <string =“”>&gt;

时间:2016-12-29 18:46:14

标签: java arraylist hashmap

我使用此代码添加到hashmap

static HashMap<Integer, ArrayList<String>> arrayMap = new HashMap<Integer, ArrayList<String>>();

ArrayList<String> list = new ArrayList<String>();
list.add("t");
list.add("b");
arrayMap.put(12, list);

ArrayList<String> list = new ArrayList<String>();
list.add("y");
list.add("x");
arrayMap.put(18, list);

此代码工作正确

但我无法在foreach中获得arrayMap的孩子

for(arrayMap .... ){
     return // 12:t,b   18:y,x
}

我的尝试:

for (int a = 0; a < arrayMap.size(); a++)
        {
            HashMap<String, Integer> tmpData = (HashMap<String, Integer>) arrayMap.get(a);
            Set<String> key = tmpData.keySet();
            Iterator it = key.iterator();
            while (it.hasNext()) {
                String hmKey = (String) it.next();
                Integer hmData = (Integer) tmpData.get(hmKey);

                System.out.println("Key: " + hmKey + " & Data: " + hmData);
                it.remove(); // avoids a ConcurrentModificationException
            }

        }

2 个答案:

答案 0 :(得分:2)

您需要遍历Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 74, in start stdout=self.log_file, stderr=self.log_file) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 707, in __init__ restore_signals, start_new_session) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1326, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'geckodriver' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> browser = webdriver.Firefox() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 140, in __init__ self.service.start() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 81, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.

https://developer.android.com/reference/java/util/Map.html#entrySet()

答案 1 :(得分:1)

您希望在嵌套循环中迭代HashMap中的每个条目,如下所示:

for(Map.Entry<Integer, ArrayList<String>> entry : arrayMap.entrySet()){
   //entry.getKey() will be each key in the HashMap
    for(String str : entry.getValue()){
         // str is one entry of the ArrayList for that Key
    }
}