2012-11-27 43 views
2

我怎样才能得到ArrayListHashMaps元素数组?我有一个带有url密钥的HashMap。该值是一个url地址。几个HashMaps存储在ArrayList。我想要的是带有所有url字符串的array。我对我找到的解决方案感到不满意,因为我认为它可以通过一些操作从ArrayList中提取出来。HashMap元素的ArrayList到数组

// Hashmap for ListView   
    ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>(); 

    // Creating JSON Parser instance 
    JSONParser jParser = new JSONParser(); 
    jParser.execute(url); 

    try { 
     JSONObject json = jParser.get(); 

     items = json.getJSONArray(TAG_ITEMS); 
     //This is the solution that I want to optimize 
     urls = new String[items.length()]; 

     // looping through All items 
     for(int i = 0; i < items.length(); i++){ 
      JSONObject c = items.getJSONObject(i); 

      // Storing each json item in variable 
      String title = c.getString(TAG_TITLE); 
      String description = c.getString(TAG_DESCRIPTION); 
      String author = c.getString(TAG_AUTHOR); 

      // Media is another JSONObject 
      JSONObject m = c.getJSONObject(TAG_MEDIA); 
      String url = m.getString(TAG_URL); 

      // creating new HashMap 
      HashMap<String, String> map = new HashMap<String, String>(); 

      // adding each child node to HashMap key => value 
      map.put(TAG_TITLE, title); 
      map.put(TAG_DESCRIPTION, description); 
      map.put(TAG_AUTHOR, author); 
      map.put(TAG_URL, url); 

      // Solution 
      urls[i] = url; 

      // adding HashList to ArrayList 
      itemsList.add(map); 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } catch (ExecutionException e) { 
     e.printStackTrace(); 
    } 

回答

3

从我可以从你的问题推断,这听起来像你”再努力做到以下几点

// Assuming previously declared and instantiated urls ArrayList with populated values in the nested HashMaps. 
ArrayList<HashMap<String, String>> urls; 
// Create a new List using HashMap.values from urls. 
List<String> urlList = new ArrayList<String>(urls.get(index).values()); 

urls.get(index).values()将返回Collection视图包含在值的在指定的ArrayList索引处,该索引将用于实例化并填充新的ArrayList

如果你想获得价值所有嵌套HashMapsurls的每个,可以以类似的方式做到这一点,但你需要在整个urls ArrayList

for (HashMap<String, String> urlValues : urls) { 
    urlList.addAll(urlValues.values()); 
} 
迭代

PS原谅我的糟糕的变量名!