简体   繁体   中英

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:

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<String, String> map = new HashMap<String, String>();

for(String key: map.keySet()) {
    Log.d("MyString", key);
}

There is keySet method in the Map interface. 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,

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. You can run a for loop over the keys Set like following:

for (String s : item.keySet()) {
  Log.d("hashmap_keys", s);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM