如何通过LinkedHashMap创建循环<string,arraylist <string>&gt;?</string,arraylist <string>

时间:2011-05-05 17:53:00

标签: java loops map linkedhashmap

请帮我创建一个LinkedHashMap<String,ArrayList<String>> h循环:

if (h.get("key1").size() == 0)
    System.out.println("There is no errors in key1.");
else
    System.out.println("ERROR: there are unexpected errors in key1.");

if (h.get("key2").size() == 0)
    System.out.println("There is no errors in key2.");
else
    System.out.println("ERROR: there are unexpected errors in key2.");

if (h.get("key3").size() == 0)
    System.out.println("There is no errors in key3.");
else
    System.out.println("ERROR: there are unexpected errors in key3.");

if (h.get("key4").size() == 0)
    System.out.println("There is no errors in key4.\n");
else
    System.out.println("ERROR: there are unexpected errors in key4.\n");

2 个答案:

答案 0 :(得分:13)

喜欢这个吗?

for (String key : h.keySet())
{
    System.out.println("Key: " + key);   
    for(String str : h.get(key))
    {
       System.out.println("\t" +str);
    }
}

编辑:

for (String key : h.keySet())
{
    if(h.get(key).size() == 0)
    {
         System.out.println("There is no errors in " + key) ;
    }
    else
    {
        System.out.println("ERROR: there are unexpected errors in " + key);
    }
}

答案 1 :(得分:7)

试试这段代码:

Map<String, ArrayList<String>> a = new LinkedHashMap<String, ArrayList<String>>();
Iterator<Entry<String,ArrayList<String>>> itr = a.entrySet().iterator();
while (itr.hasNext()) {
    Entry<String,ArrayList<String>> entry = itr.next();
    String key = entry.getKey();
    System.out.println("key: " + key);
    List<String> list = entry.getValue();
    System.out.println("value: " + list);
}