问题描述
HashMap< String,我试图使用HashMap将唯一字符串映射到字符串ArrayList,的ArrayList<字符串>>
基本上,我希望能够通过数字访问密钥,而不是使用密钥的名称。我希望能够访问所述密钥的值,以迭代它。我想像这样:
$ p $ for(在我的hashmap中的所有键){
for(int i = 0; i< myhashmap.currentKey.getValue.size(); i ++){
//使用hashmaps元素
}
}
有没有一种简单的方法可以做到这一点?
你可以通过调用 map.keySet()
遍历键,或者通过调用 map.entrySet()
。 (Map.Entry< String,List< String>>> entry:map。)对于条目的迭代可能会更快。
List< String> list = entry.getValue();
//对列表做些事
}
如果你想确保你按照与插入它们相同的顺序遍历这些键,然后使用 LinkedHashMap
。
顺便说一下,我建议将地图的声明类型更改为< String,List< String>>
。总是最好根据界面而不是实现声明类型。
I am trying to use a HashMap to map a unique string to a string ArrayList like this:
HashMap<String, ArrayList<String>>
Basically, I want to be able to access the keys by number, not by using the key's name. And I want to be able to access said key's value, to iterate over it. I'm imagining something like this:
for(all keys in my hashmap) {
for(int i=0; i < myhashmap.currentKey.getValue.size(); i++) {
// do things with the hashmaps elements
}
}
Is there an easy way to do this?
You can iterate over keys by calling map.keySet()
, or iterate over the entries by calling map.entrySet()
. Iterating over entries will probably be faster.
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> list = entry.getValue();
// Do things with the list
}
If you want to ensure that you iterate over the keys in the same order you inserted them then use a LinkedHashMap
.
By the way, I'd recommend changing the declared type of the map to <String, List<String>>
. Always best to declare types in terms of the interface rather than the implementation.
这篇关于Java HashMap:如何通过索引获取键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!