2014-02-18 72 views
-1

我如何打印所有的值從下面的HashMap如何使用循環

ServletContext appScope = request.getServletContext(); 
     Map<String, List<String>> onLine = (HashMap<String, List<String>>)appScope.getAttribute("User"); 
     if(onLine != null) { 
      out.print(onLine.get("1")); 
     } 

回答

1
if (onLine != null) { 
    for (String k : onLine.keySet()) { 
     for (String v : onLine.get(k)) { 
      out.print(v); 
     } 
    } 
} 
1

嘗試使用此方法得到的HashMap值:

if (onLine != null) { 
    for (String key : onLine.keySet()) { 
     for (List<String> val : onLine.get(key)) { 
      for(String str : val){ 
       System.out.print(str); 
      } 
     } 
    } 
} 

這將打印的所有字符串在地圖。

+0

這個答案其實是錯誤的 –

2

java.util.Map有隻爲這一個值()方法:

for(List<String> nextArray : onLine.values()) { 
    for(String nextString : nextArray) { 
     out.print(nextString); 
    } 
} 
0

,如果你需要同時鍵和值:

for(Map.Entry<String, List<String>> e : yourMap.entrySet()) 
    System.out.println("key=" + e.key() + ", value=" + e.value()); 
0

我寫了一個演示,你可以嘗試

public static void main(String[] args) { 

     Map<String, Integer> map = new HashMap<String, Integer>(); 
     map.put("k1", 1); 
     map.put("k2", 2); 
     map.put("k3", 3); 
     map.put("k4", 4); 
     map.put("k5", 5); 

     Set<String> keys = map.keySet(); 
     for(String key:keys) { 
      System.out.println("key:" + key); 
      System.out.println("value:" + map.get(key)); 
     } 
}