2011-05-05 72 views
7

请帮我通过LinkedHashMap<String,ArrayList<String>> h创建一个循环:如何通过LinkedHashMap <String,ArrayList <String>>创建一个循环?

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"); 

回答

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); 
    } 
} 
+0

你可以加我的确切消息到您的循环? – Prostak 2011-05-05 18:03:28

+0

@Prostak检查我的编辑。听起来就是你想要的。 – 2011-05-05 18:06:19

+2

有点迟了,但是按照插入顺序返回还是必须使用迭代器? 'LinkedHashMap'的javadocs和'HashMap'的javadocs相同。 – edthethird 2013-04-11 02:02:53

6

试试这个代码:

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); 
} 
+0

这会返回到插入顺序吗? – Gopinath 2013-02-27 14:24:22

+0

是的,它会确保插入顺序,因为在这里使用LinkedHashMap。 – anubhava 2013-02-27 14:58:07

3

在Java8另一种方法是用foreach()方法

Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>(); 
test1.forEach((key,value) -> { 
    System.out.println(key + " -> " + value); 
}); 
相关问题