【发布时间】:2012-08-08 17:44:01
【问题描述】:
我的代码中有一个LinkedHashMap:
protected LinkedHashMap<String, String> profileMap;
我想打印profileMap 中存在的所有键。如何使用Iterator 或循环来做到这一点?
【问题讨论】:
标签: java android hashmap linkedhashmap
我的代码中有一个LinkedHashMap:
protected LinkedHashMap<String, String> profileMap;
我想打印profileMap 中存在的所有键。如何使用Iterator 或循环来做到这一点?
【问题讨论】:
标签: java android hashmap linkedhashmap
您应该从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 */
}
然而,编译时两者或多或少是相同的。
【讨论】:
cursor 的范围)。
final,但我看不出为什么——尤其是如果只打印密钥。如果出于某种原因他需要字段是可变的,他可以删除final,因为这只是一个模板。
您可以遍历Map Entries,您可以根据自己的选择选择打印e.getKey()或e.getValue()。
for(Map.Entry<String, String> e : map.entrySet()) {
System.out.println(e.getKey());
}
【讨论】: