2016-01-02 61 views
0

我有一个for循环,并且将值添加到HashMap for循环中。基本上我有一个帖子,它有评论。一个职位有8点意见,我需要我的HashMap的内容看,如下图所示:如何在Android中的for循环的每次迭代中为HashMap添加值

PostId1, comment1 
PostId1, comment2 
PostId1, comment3 
PostId1, comment4 
PostId1, comment5 
PostId1, comment6 
PostId1, comment7 
PostId1, comment8 

但是,现在我的HashMap中只包含第一个值。只有在第一次迭代中,值才会被添加到HashMap中,我如何在所有8次迭代中为hashmap添加值。

PS:所有八个值的PostID应该相同。

我当前的代码:

for (int i2 = 0; i2 < conversationArray.length(); i2++) { 
    JSONObject conversationArray1 = conversationArray.getJSONObject(i2); 
    contentConversation = conversationArray1.getString("content"); 
    commenterId = conversationArray1.getString("commenterId"); 
    commenterName = conversationArray1.getString("commenterName"); 
    commenterPhotos = conversationArray1.getString("commenterPhotos"); 
    postIdForComments = conversationArray1.getString("postId"); 
    lastDateUpdatedConversation = conversationArray1.getString("lastDateUpdated"); 
    dateCreatedConversation = conversationArray1.getString("dateCreated"); 
    commentDescription.add(contentConversation); 
    commentUserName.add(commenterName); 
    commentProfileImageLink.add(commenterPhotos); 

    commentProfileImageHashMap.put(postIdForComments, commenterPhotos); 
    commentDescriptionHashMap.put(postIdForComments, contentConversation); 
    commentUserNameHashMap.put(postIdForComments, commenterName); 
} 

请让我知道什么样的变化,我应该让我的代码,实现我的目标。所有建议都欢迎。

+1

你似乎不清楚包含HashMap是如何工作 - 项对的,关键的第一个项目,**必须* *是唯一的,否则你不应该使用HashMap。可能你想使用的是'Map >',它被实现为'HashMap >'。 –

+0

@HovercraftFullOfEels好的。我会尽力实现这一点。 – Kiran

回答

1

使用Map<String, List<String>>存储的每个职位评论列表:

Map<String, List<String>> mapOfPosts = new HashMap<>(); 

List<String> post1Comments = new ArrayList<>(); 

// Collect comments of a certain post 
post1Comments.add("comment1"); 
post1Comments.add("comment2"); 
... 

// Attach comments to post 
mapOfPosts.put("post1", post1Comments); 

// Repeat this for all posts 
+1

滑入之前我可以作为副本关闭。类似的问题有很多类似的答案,我们是否真的需要更多?例如[本Google网站搜索](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=hashmap+string+key+arraylist+value+site :http:%2F%2Fstackoverflow.com%2F)返回了近24,000次点击,现在该网站已有24,001次。 –

相关问题