[英]How can I get a List<String> of the keys from a HashMap<String, String>?
I have a HashMap<String, String> item
and I need to get all of the keys from it in an array so I can do this: 我有一个
HashMap<String, String> item
,我需要从数组中获取所有键,所以可以这样做:
for (String s : mapKeys)
{
Log.d("MyString", s);
}
How can I do this? 我怎样才能做到这一点? Thanks!
谢谢!
for (String s : item.keySet()) {
Log.d("MyString", s);
}
You need to use Map#keySet
method that gives you a Set
of keys
in HashMap: - 您需要使用
Map#keySet
方法,该方法为您在HashMap中提供一Set
keys
:-
Map<String, String> map = new HashMap<String, String>();
for(String key: map.keySet()) {
Log.d("MyString", key);
}
There is keySet
method in the Map
interface. Map
界面中有keySet
方法。 To obtain an array (as you mention in your question) you could use 要获取数组 (如您在问题中提到的),可以使用
item.keySet().toArray(new String[item.size()])
But you could just as easily iterate over the keySet
itself, 但是您可以轻松地遍历
keySet
本身,
for (String s : item.keySet()) {
...
}
try: 尝试:
for (String key : myHashMap.keySet()) {
}
As mentioned in comment check out http://developer.android.com/reference/java/util/HashMap.html#keySet () which return the Set
of keys. 如评论中所述,请查看http://developer.android.com/reference/java/util/HashMap.html#keySet (),它返回键
Set
。 You can run a for loop over the keys Set
like following: 您可以对键
Set
运行for循环,如下所示:
for (String s : item.keySet()) {
Log.d("hashmap_keys", s);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.