简体   繁体   English

我如何获得清单 <String> HashMap中的键 <String, String> ?

[英]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.

相关问题 如何将Json字符串转换为列表 <HashMap<String, String> &gt;? - How can I convert Json String to List<HashMap<String, String>>? 我有两个 hashmap HashMap <string,list<string> &gt; 在这种格式下,如何比较两个值是否相同或不同的键</string,list<string> - I have two hashmap HashMap<String,List<String>> in this format how to compare both the values are same or not with same keys 如何从 Hashmap 中获取值<String, Object> ? - How can I get a value from Hashmap<String, Object>? 如何在列表中存储HashMap <String,ArrayList <String >>? - How can I store HashMap<String, ArrayList<String>> inside a list? 从ArrayList获取密钥 <HashMap<String, String> &gt;&gt;放入另一个数组 - Get Keys from ArrayList<HashMap<String, String>>> into another array 如何从Hashmap获取ArrayList <String String> - How to get ArrayList from Hashmap<String String> 如何获取列表<E>来自 HashMap <String,List<E> &gt; - How to get a List<E> from a HashMap<String,List<E>> 如何在Hashmap中修剪字符串键 - How Trim String keys in Hashmap 从嵌套的 HashMap 中获取 HashMapsValues <string, hashmap<string, string> &gt; 根据列表过滤<string></string></string,> - Get HashMapsValues from nested HashMap<String, HashMap<String, String>> filtered against a List<String> 如何在hashmap中存储值 <String, List<Integer> &gt; - How can I store values in a hashmap with <String, List<Integer>>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM