2012-11-27 3 views
2

ArrayList의 요소 배열을 어떻게 얻을 수 있습니까? HashMaps? 나는 그것에 대한 열쇠가있는 HashMap을 가지고있다. 값은 URL 주소입니다. 여러 HashMapsArrayList에 저장됩니다. 내가 원하는 것은 모든 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을 인스턴스화하고 채우는 데 사용됩니다. 당신이 중첩 HashMaps 또는 urls 내에서 값의 모든를 얻을하려는 경우

, 당신은 유사한 방식으로 그렇게 할 수 있습니다,하지만 당신은 전체 urls ArrayList

for (HashMap<String, String> urlValues : urls) { 
    urlList.addAll(urlValues.values()); 
} 
을 반복해야합니다

PS 내 나쁜 변수 이름을 용서하십시오!

관련 문제