【问题标题】:How to add values to HashMap in every iteration of for loop in android [duplicate]如何在android中for循环的每次迭代中向HashMap添加值[重复]
【发布时间】:2016-04-06 11:33:04
【问题描述】:

我有一个 for 循环,我在 for 循环中向 HashMap 添加值。基本上我有一个帖子,它有 cmets。一篇文章有​​ 8 个 cmets,我需要我的 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);
}

请让我知道我应该对代码进行哪些更改以实现我的目标。欢迎所有建议。

【问题讨论】:

  • 您似乎不清楚 HashMap 的工作原理——条目对的第一项,即键,必须是唯一的,否则您不应该使用 HashMap .您可能想要使用的是作为HashMap&lt;String, ArrayList&lt;String&gt;&gt; 实现的Map&lt;String, List&lt;String&gt;&gt;
  • @HovercraftFullOfEels 好的。我会努力实现的。

标签: java android hashmap


【解决方案1】:

使用Map&lt;String, List&lt;String&gt;&gt;存储每个帖子的 cmets 列表

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

【讨论】:

  • 在我作为副本关闭之前溜进去了。类似的问题有很多类似的答案,我们真的还需要一个吗?例如,this Google search of this site 返回了近 24,000 次点击,现在该网站有 24,001 次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
  • 2015-03-19
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多