2013-02-08 54 views
0

我有一個HashMap和我循環是這樣的:如何添加HashMap中值到一個ArrayList

for(HashMap<String, Integer> aString : value){ 
       System.out.println("key : " + key + " value : " + aString); 

      } 

我得到的結果爲:

key : My Name value : {SKI=7, COR=13, IN=30} 

現在我需要分開`SKI ,COR和IN分成3個不同的ArrayLists及其相應的值?怎麼做?

+0

是您的數據總是JSON? – 2013-02-08 13:22:59

+0

我不能使用JSON?不能以正常的方式做到這一點? – Goofy 2013-02-08 13:28:09

+0

這個問題如何與Android相關? – iargin 2013-02-08 13:29:38

回答

0

如果您的數據始終是JSON,您可以根據您通常會使用JSON只是對其進行解碼:

ArrayList<Integer> array = new ArrayList<Integer>(); 
JSONArray json = new JSONArray(aString); 
for (int i =0; i< json.length(); i++) { 
    array.add(json.getInt(i)); 
} 
+0

我不能使用JSON?不能以正常的方式做到這一點? – Goofy 2013-02-08 13:27:36

+0

你將不得不手動解析字符串。分割',',然後通過'='分割每個元組。 – 2013-02-08 13:29:52

0

我不是超級確認的是您的HashMap包含因爲你的代碼是如此的短暫,但它幾乎看起來像它給你的哈希映射的toString()。通過一個HashMap迭代的最好辦法是:

Map mp; 
    ..... 
    Iterator it = mp.entrySet().iterator(); 
    while (it.hasNext()) { 
     Map.Entry pairs = (Map.Entry)it.next(); 
     System.out.println(pairs.getKey() + " = " + pairs.getValue()); 
     String key = pairs.getKey(); 
     String value = pairs.getValue(); 
     //Do something with the key/value pair 
    } 

但如果你是通過你的HashMap迭代正確然後下面是手動解析字符串轉換成三個不同的ArrayList的解決方案,這可能是最安全的方法它。

ArrayList <String> ski = new ArrayList <String>(); 
ArrayList <String> cor = new ArrayList <String>(); 
ArrayList <String> in = new ArrayList <String>(); 

for (HashMap < String, Integer > aString: value) { 
    System.out.println("key : " + key + " value : " + aString); 
    aString.replace("{", ""); 
    aString.replace("}", ""); 
    String[] items = aString.split(", "); 
    for (String str: items) { 
     if (str.contains("SKI")) { 
      String skiPart = str.split("="); 
      if (skiPart.length == 2) ski.add(skiPart[1]); 
     } 
     elseif(str.contains("COR")) { 
      String corPart = str.split("="); 
      if (corPart.length == 2) cor.add(corPart[1]); 
     } 
     elseif(str.contains("IN")) { 
      String inPart = str.split("="); 
      if (inPart.length == 2) in.add(inPart[1]); 
     } 
    } 

} 
0

這裏是一個ArrayList(或目錄)全HashMaps這樣的:

ArrayList<HashMap<String, Object>> userNotifications = new ArrayList<HashMap<String, Object>>(); 
int count = 0; 

HashMap<String, Object> notificationItem = new HashMap<String, Object>(); 
notificationItem.put("key1", "value1"); 
notificationItem.put("key2", "value2"); 
userNotifications.add(count, notificationItem); 
count++; 

然後檢索值:

ArrayList<HashMap<String, Object>> resultGetLast5PushNotificationsByUser = new ArrayList<HashMap<String, Object>>(); 

resultGetLast5PushNotificationsByUser = methodThatReturnsAnArrayList(); 
HashMap<String, Object> item1= resultGetLast5PushNotificationsByUser.get(0); 
String value1= item1.get("key1"); 
String value2= item1.get("key2"); 
HashMap<String, Object> item1= resultGetLast5PushNotificationsByUser.get(1); 
String value1= item1.get("key1"); 
String value2= item1.get("key2");