【问题标题】:Print all keys in a LinkedHashMap in Android在 Android 中打印 LinkedHashMap 中的所有键
【发布时间】:2012-08-08 17:44:01
【问题描述】:

我的代码中有一个LinkedHashMap

 protected LinkedHashMap<String, String> profileMap;

我想打印profileMap 中存在的所有键。如何使用Iterator 或循环来做到这一点?

【问题讨论】:

标签: java android hashmap linkedhashmap


【解决方案1】:

您应该从Map.keySet 迭代Set

for (final String key : profileMap.keySet()) {
  /* print the key */
}

明确使用Iterator

final Iterator<String> cursor = profileMap.keySet().iterator();
while (cursor.hasNext()) {
  final String key = cursor.next();
  /* print the key */
}

然而,编译时两者或多或少是相同的。

【讨论】:

  • 你可以摆脱所有的决赛。同样对于迭代器,您还可以使用 for 循环(更好,因为它限制了cursor 的范围)。
  • @SteveKuo 当然你可以删除final,但我看不出为什么——尤其是如果只打印密钥。如果出于某种原因他需要字段是可变的,他可以删除final,因为这只是一个模板。
  • @user268397 因为您在这里显得较新,请不要忘记标记答案accepted,这有助于解决问题。
【解决方案2】:

您可以遍历Map Entries,您可以根据自己的选择选择打印e.getKey()e.getValue()

   for(Map.Entry<String, String> e : map.entrySet()) {
        System.out.println(e.getKey());
    }

【讨论】:

  • 但如果您只对键感兴趣...只需使用 keySet()
猜你喜欢
  • 2012-02-13
  • 2019-11-28
  • 2013-07-25
  • 2014-05-04
  • 1970-01-01
  • 2016-02-01
  • 2018-05-16
  • 1970-01-01
  • 2018-04-23
相关资源
最近更新 更多