2011-05-05 62 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); 
}); 
相關問題